🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(file-viewer): preview and play audio files (#22918)
Rdmclin26dde649a7c77
diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex ec5e5becd4e..8d96a06cce9 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -468,6 +468,7 @@"pageList.transferWarning": "This is a one-way move; reverting requires another move.","pageList.untitled": "Untitled","portal.openInPageEditor": "Edit in Page",+ "preview.audioLoadFailed": "This audio could not be played in the browser. Download it to listen.","preview.downloadFile": "Download File","preview.raw": "Raw","preview.render": "Preview",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 5cb7daf836a..57dd069f85a 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -468,6 +468,7 @@"pageList.transferWarning": "移动后如需恢复原位置,请手动移回。","pageList.untitled": "无标题","portal.openInPageEditor": "在文稿中编辑",+ "preview.audioLoadFailed": "浏览器无法播放这段音频,可以下载后收听。","preview.downloadFile": "下载文件","preview.raw": "原文","preview.render": "预览",diff --git a/package.json b/package.jsonindex 25e4908ad1b..d073378d007 100644--- a/package.json+++ b/package.json@@ -337,6 +337,7 @@"@lobehub/editor": "7.2.1","@lobehub/icons": "^6.13.0","@lobehub/market-sdk": "0.46.0",+ "@lobehub/tts": "^6.1.0","@lobehub/ui": "^6.13.1","@modelcontextprotocol/client": "~2.4.0","@modelcontextprotocol/ext-apps": "^2.0.3",diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex a908dc8cb5f..013506ff30d 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -562,6 +562,8 @@ export default {'resourceList.viewTransferred': 'View','portal.openInPageEditor': 'Edit in Page','preview.tooLarge': 'This file is too large to preview. Download it to view its contents.',+ 'preview.audioLoadFailed':+ 'This audio could not be played in the browser. Download it to listen.','preview.downloadFile': 'Download File','preview.raw': 'Raw','preview.render': 'Preview',diff --git a/src/features/FileViewer/Renderer/Audio/index.tsx b/src/features/FileViewer/Renderer/Audio/index.tsxnew file mode 100644index 00000000000..5b3d9facc4a--- /dev/null+++ b/src/features/FileViewer/Renderer/Audio/index.tsx@@ -0,0 +1,93 @@+'use client';++import { AudioPlayer, useAudioPlayer } from '@lobehub/tts/react';+import { Button, Center, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import FileIcon from '@/components/FileIcon';+import { downloadFile } from '@/utils/client/downloadFile';++const styles = stylex.create({+ card: {+ width: '100%',+ maxWidth: '520px',+ padding: '24px',+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorBgContainer,+ boxShadow: cssVar.boxShadowTertiary,+ },+ name: {+ overflow: 'hidden',+ minWidth: 0,+ fontWeight: 500,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+});++interface AudioViewerProps {+ fileId: string;+ fileName?: string;+ url: string | null;+}++const AudioViewer = memo<AudioViewerProps>(({ url, fileName }) => {+ const { t } = useTranslation('file');+ const [downloading, setDownloading] = useState(false);+ const name = fileName || 'audio';++ // Streaming lets the browser range-request the file and play signed storage+ // URLs that send no CORS headers.+ const { isLoading, error, ...audio } = useAudioPlayer({+ filename: name,+ src: url ?? undefined,+ streaming: true,+ });++ const handleDownload = useCallback(async () => {+ if (!url) return;+ setDownloading(true);+ try {+ await downloadFile(url, name);+ } finally {+ setDownloading(false);+ }+ }, [url, name]);++ if (!url) return null;++ return (+ <Center height={'100%'} padding={16} width={'100%'}>+ <Flexbox gap={16} id="audio-renderer" {...stylex.props(styles.card)}>+ <Flexbox horizontal align={'center'} gap={12}>+ <FileIcon fileName={name} size={40} />+ <Text title={name} {...stylex.props(styles.name)}>+ {name}+ </Text>+ </Flexbox>+ <AudioPlayer+ audio={{ ...audio, download: handleDownload, error }}+ isLoading={isLoading}+ showDownload={!error}+ timeType={'combine'}+ // AudioPlayer treats a zero duration as "not loaded yet"; a stream whose+ // length stays unknown still has to start playing.+ onInitPlay={audio.play}+ />+ {error && (+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>+ <Text type={'secondary'}>{t('preview.audioLoadFailed')}</Text>+ <Button loading={downloading} onClick={handleDownload}>+ {t('preview.downloadFile')}+ </Button>+ </Flexbox>+ )}+ </Flexbox>+ </Center>+ );+});++export default AudioViewer;diff --git a/src/features/FileViewer/fileType.test.ts b/src/features/FileViewer/fileType.test.tsindex 70492c27f3f..9a9bdb77d3f 100644--- a/src/features/FileViewer/fileType.test.ts+++ b/src/features/FileViewer/fileType.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { isPdfFile } from './fileType';+import { isAudioFile, isPdfFile } from './fileType';describe('isPdfFile', () => {it('detects PDF files by MIME type', () => {@@ -51,3 +51,31 @@ describe('isPdfFile', () => {expect(isPdfFile({})).toBe(false);});});++describe('isAudioFile', () => {+ it('detects audio files by MIME type', () => {+ expect(isAudioFile({ fileType: 'audio/mpeg' })).toBe(true);+ expect(isAudioFile({ fileType: 'audio/wav' })).toBe(true);+ expect(isAudioFile({ fileType: 'AUDIO/OGG; codecs=opus' })).toBe(true);+ expect(isAudioFile({ fileType: 'mp3' })).toBe(true);+ });++ it('detects audio files by extension when the MIME type is missing or generic', () => {+ expect(isAudioFile({ fileName: 'minimax-speech-2.8-turbo-sample.mp3' })).toBe(true);+ expect(isAudioFile({ fileName: 'voice.M4A' })).toBe(true);+ expect(isAudioFile({ fileName: 'voice.flac', fileType: 'application/octet-stream' })).toBe(+ true,+ );+ });++ it('leaves container formats without an audio MIME type to the video renderer', () => {+ expect(isAudioFile({ fileName: 'clip.ogg' })).toBe(false);+ expect(isAudioFile({ fileName: 'clip.webm', fileType: 'video/webm' })).toBe(false);+ expect(isAudioFile({ fileType: 'video/ogg' })).toBe(false);+ });++ it('rejects non-audio files', () => {+ expect(isAudioFile({ fileName: 'notes.md', fileType: 'text/markdown' })).toBe(false);+ expect(isAudioFile({})).toBe(false);+ });+});diff --git a/src/features/FileViewer/fileType.ts b/src/features/FileViewer/fileType.tsindex 264c1e609f1..7fe1083e1d3 100644--- a/src/features/FileViewer/fileType.ts+++ b/src/features/FileViewer/fileType.ts@@ -29,3 +29,23 @@ export const isPdfFile = ({ fileName, fileType, path }: PdfFileFields): booleanPDF_FILE_EXTENSIONS.some((extension) => candidate.endsWith(extension)),);};++// Formats the browser `<audio>` element can play. `.ogg` / `.webm` stay with the+// video renderer unless the MIME type says audio, since they are container formats.+const AUDIO_FILE_EXTENSIONS = ['.aac', '.flac', '.m4a', '.mp3', '.oga', '.opus', '.wav', '.weba'];+const AUDIO_FILE_TYPES = new Set(['aac', 'flac', 'm4a', 'mp3', 'oga', 'opus', 'wav', 'weba']);++export const isAudioFile = ({ fileName, fileType }: Omit<PdfFileFields, 'path'>): boolean => {+ const normalizedFileType = normalizeFileType(fileType);++ if (normalizedFileType) {+ if (normalizedFileType.startsWith('audio/')) return true;+ if (AUDIO_FILE_TYPES.has(normalizedFileType)) return true;+ }++ if (!fileName) return false;++ const candidate = stripUrlSuffix(fileName).toLowerCase();++ return AUDIO_FILE_EXTENSIONS.some((extension) => candidate.endsWith(extension));+};diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsxindex a2299fd980b..c5b1f0fb311 100644--- a/src/features/FileViewer/index.tsx+++ b/src/features/FileViewer/index.tsx@@ -9,8 +9,9 @@ import AsyncError from '@/components/AsyncError';import { isHtmlFile } from '@/components/HtmlPreview';import { type FileListItem } from '@/types/files';-import { isPdfFile } from './fileType';+import { isAudioFile, isPdfFile } from './fileType';import NotSupport from './NotSupport';+import AudioViewer from './Renderer/Audio';import CodeViewer from './Renderer/Code';import HTMLViewer from './Renderer/HTML';import ImageViewer from './Renderer/Image';@@ -193,6 +194,11 @@ const FileViewer = memo<FileViewerProps>((props) => {);}+ // Audio files - checked before video so `audio/ogg` / `audio/webm` play as audio.+ if (isAudioFile({ fileName: name, fileType })) {+ return <AudioViewer fileId={id} fileName={name} key={url} url={url} />;+ }+// Video filesif (matchesFileType(fileType, name, VIDEO_EXTENSIONS, VIDEO_MIME_TYPES)) {return <VideoViewer fileId={id} url={url} />;