Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(editor): import external audio files as audio-kind assets

Benjamin Freemanc542fe026177
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.ts
index 6cbdb97c9..91e780acf 100644
--- a/electron/ai-edition/document-service.test.ts
+++ b/electron/ai-edition/document-service.test.ts
@@ -280,6 +280,48 @@ describe("DocumentService", () => {
expect(after.project.primaryAssetId).toBe(first.project.primaryAssetId);
expect(after.assets).toHaveLength(2);
});
+
+ // Issue #350 — external audio import (voiceover / BGM / SFX).
+ it("appends an audio asset without claiming the primary slot", async () => {
+ const doc = await service.createProject("P");
+ const updated = await service.addAsset(doc.project.id, {
+ path: "/tmp/voiceover.mp3",
+ kind: "audio",
+ });
+ expect(updated.assets).toHaveLength(1);
+ expect(updated.assets[0]?.kind).toBe("audio");
+ // An audio-only file must never become the project's primary asset, even
+ // when it is the first file added to an otherwise-empty project.
+ expect(updated.project.primaryAssetId).toBeUndefined();
+ });
+
+ it("keeps the existing video primary when an audio track is added", async () => {
+ const doc = await service.createProject("P");
+ const withVideo = await service.addAsset(doc.project.id, { path: "/tmp/screen.mp4" });
+ const primary = withVideo.project.primaryAssetId;
+ const withAudio = await service.addAsset(doc.project.id, {
+ path: "/tmp/bgm.wav",
+ kind: "audio",
+ });
+ expect(withAudio.project.primaryAssetId).toBe(primary);
+ expect(withAudio.assets).toHaveLength(2);
+ });
+
+ it("rejects unsupported audio extensions", async () => {
+ const doc = await service.createProject("P");
+ await expect(
+ service.addAsset(doc.project.id, { path: "/tmp/clip.mp4", kind: "audio" }),
+ ).rejects.toBeInstanceOf(ProjectFileError);
+ });
+
+ it("accepts a video extension under the default kind but not as audio", async () => {
+ const doc = await service.createProject("P");
+ // The same extension routing works in reverse: an .mp3 is fine as audio
+ // but rejected as video (covered above), and an .mp4 is the opposite.
+ await expect(
+ service.addAsset(doc.project.id, { path: "/tmp/a.mp3", kind: "audio" }),
+ ).resolves.toBeDefined();
+ });
});
describe("removeAsset", () => {
diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.ts
index 3c93e3bc0..f519379e4 100644
--- a/electron/ai-edition/document-service.ts
+++ b/electron/ai-edition/document-service.ts
@@ -38,6 +38,9 @@ export interface ProjectSummary {
export interface AddAssetInput {
path: string;
label?: string;
+ // "audio" imports an external voiceover / BGM / SFX file (issue #350).
+ // Defaults to "video" when omitted, so existing callers are unaffected.
+ kind?: "video" | "audio";
}
export class DocumentNotFoundError extends Error {
@@ -72,6 +75,24 @@ function isSupportedVideoPath(filePath: string): boolean {
return SUPPORTED_VIDEO_EXTENSIONS.has(ext);
}
+// Imported audio (issue #350). Decoding is handled downstream by the same
+// WebCodecs / ffmpeg paths that read a video's audio track, so this list is the
+// container formats decodeAudioData and the compositor can open.
+const SUPPORTED_AUDIO_EXTENSIONS = new Set([
+ ".mp3",
+ ".wav",
+ ".m4a",
+ ".aac",
+ ".flac",
+ ".ogg",
+ ".opus",
+]);
+
+function isSupportedAudioPath(filePath: string): boolean {
+ const ext = path.extname(filePath).toLowerCase();
+ return SUPPORTED_AUDIO_EXTENSIONS.has(ext);
+}
+
function safeProjectId(raw: string): string {
// ponytail: project ids are uuid-prefixed strings (e.g. "proj_<uuid>"). Reject
// anything that smells like path traversal before we ever touch the disk.
@@ -283,7 +304,15 @@ export class DocumentService {
if (!input.path) {
throw new ProjectFileError("Asset path is required.", projectId);
}
- if (!isSupportedVideoPath(input.path)) {
+ const kind = input.kind ?? "video";
+ if (kind === "audio") {
+ if (!isSupportedAudioPath(input.path)) {
+ throw new ProjectFileError(
+ `Unsupported audio extension: ${path.extname(input.path)} (supported: ${[...SUPPORTED_AUDIO_EXTENSIONS].join(", ")})`,
+ projectId,
+ );
+ }
+ } else if (!isSupportedVideoPath(input.path)) {
throw new ProjectFileError(
`Unsupported video extension: ${path.extname(input.path)} (supported: ${[...SUPPORTED_VIDEO_EXTENSIONS].join(", ")})`,
projectId,
@@ -300,18 +329,24 @@ export class DocumentService {
}
const asset: AxcutAsset = {
id: createId("asset"),
- kind: "video",
+ kind,
label: input.label?.trim() || path.basename(absolutePath),
originalPath: absolutePath,
sizeBytes,
cameraTrack: null,
};
+ // An audio import is an overlay, never the thing the timeline is built
+ // around, so it must not claim the empty primaryAssetId slot — otherwise the
+ // first file dropped into a fresh project (a BGM track) would become its
+ // primary asset and the editor would try to lay out clips from a file with
+ // no video.
+ const claimsPrimary = kind !== "audio" && !doc.project.primaryAssetId;
const next: AxcutDocument = {
...doc,
assets: [...doc.assets, asset],
project: {
...doc.project,
- ...(doc.project.primaryAssetId ? {} : { primaryAssetId: asset.id }),
+ ...(claimsPrimary ? { primaryAssetId: asset.id } : {}),
updatedAt: new Date().toISOString(),
},
};
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index e140a4e37..831e1a790 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -289,6 +289,14 @@ interface Window {
name?: string;
canceled?: boolean;
}>;
+ // Import an external audio file (voiceover / BGM / SFX) — issue #350.
+ openAudioFilePicker: () => Promise<{
+ success: boolean;
+ path?: string;
+ name?: string;
+ canceled?: boolean;
+ message?: string;
+ }>;
setCurrentVideoPath: (path: string) => Promise<{ success: boolean }>;
setCurrentRecordingSession: (
session: import("../src/lib/recordingSession").RecordingSession | null,
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index aa2014670..52d38db10 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -186,6 +186,23 @@ function hasAllowedImportVideoExtension(filePath: string): boolean {
return ALLOWED_IMPORT_VIDEO_EXTENSIONS.has(path.extname(filePath).toLowerCase());
}
+// Imported audio (issue #350). Kept separate from the video set so the two
+// pickers stay honest — an audio picker must not approve a video path and vice
+// versa. Mirrors SUPPORTED_AUDIO_EXTENSIONS in the document service.
+const ALLOWED_IMPORT_AUDIO_EXTENSIONS = new Set([
+ ".mp3",
+ ".wav",
+ ".m4a",
+ ".aac",
+ ".flac",
+ ".ogg",
+ ".opus",
+]);
+
+function hasAllowedImportAudioExtension(filePath: string): boolean {
+ return ALLOWED_IMPORT_AUDIO_EXTENSIONS.has(path.extname(filePath).toLowerCase());
+}
+
function runProcess(
command: string,
args: string[],
@@ -282,8 +299,13 @@ async function prepareSupplementalPreviewAudioTrack(videoPath: string) {
return { success: true, path: pathToFileURL(outputPath).toString() };
}
-async function approveReadableVideoPath(
- filePath?: string | null,
+// Shared core behind the media path approvers. `hasAllowedExtension` is the ONLY
+// thing that differs between video and audio imports, so it is the single knob:
+// an already-approved path passes regardless, otherwise the extension gate,
+// optional trusted-dir confinement, and a stat check decide whether to approve.
+async function approveReadableMediaPath(
+ filePath: string | null | undefined,
+ hasAllowedExtension: (p: string) => boolean,
trustedDirs?: string[],
): Promise<string | null> {
const normalizedPath = normalizeVideoSourcePath(filePath);
@@ -295,7 +317,7 @@ async function approveReadableVideoPath(
return normalizedPath;
}
- if (!hasAllowedImportVideoExtension(normalizedPath)) {
+ if (!hasAllowedExtension(normalizedPath)) {
return null;
}
@@ -322,6 +344,20 @@ async function approveReadableVideoPath(
return normalizedPath;
}
+function approveReadableVideoPath(
+ filePath?: string | null,
+ trustedDirs?: string[],
+): Promise<string | null> {
+ return approveReadableMediaPath(filePath, hasAllowedImportVideoExtension, trustedDirs);
+}
+
+function approveReadableAudioPath(
+ filePath?: string | null,
+ trustedDirs?: string[],
+): Promise<string | null> {
+ return approveReadableMediaPath(filePath, hasAllowedImportAudioExtension, trustedDirs);
+}
+
function resolveRecordingOutputPath(fileName: string): string {
const trimmed = fileName.trim();
if (!trimmed) {
@@ -3636,6 +3672,54 @@ export function registerIpcHandlers(
}
});
+ // Import an external audio file (voiceover / BGM / SFX) — issue #350. Mirrors
+ // the video picker but approves against the audio extension set; the returned
+ // path is added to the project as a `kind: "audio"` asset by the renderer.
+ ipcMain.handle("open-audio-file-picker", async () => {
+ try {
+ const dialogOptions = buildDialogOptions(
+ {
+ title: mainT("dialogs", "fileDialogs.selectAudio"),
+ defaultPath: RECORDINGS_DIR,
+ filters: [
+ {
+ name: mainT("dialogs", "fileDialogs.audioFiles"),
+ extensions: ["mp3", "wav", "m4a", "aac", "flac", "ogg", "opus"],
+ },
+ { name: mainT("dialogs", "fileDialogs.allFiles"), extensions: ["*"] },
+ ],
+ properties: ["openFile"],
+ },
+ getMainWindow(),
+ );
+ const result = await dialog.showOpenDialog(dialogOptions);
+
+ if (result.canceled || result.filePaths.length === 0) {
+ return { success: false, canceled: true };
+ }
+
+ const normalizedPath = await approveReadableAudioPath(result.filePaths[0]);
+ if (!normalizedPath) {
+ return {
+ success: false,
+ message: "Selected file is not a supported readable audio file",
+ };
+ }
+
+ return {
+ success: true,
+ path: normalizedPath,
+ };
+ } catch (error) {
+ console.error("Failed to open audio file picker:", error);
+ return {
+ success: false,
+ message: "Failed to open audio file picker",
+ error: String(error),
+ };
+ }
+ });
+
ipcMain.handle("reveal-in-folder", async (_, filePath: string) => {
try {
// showItemInFolder returns nothing, it throws on error
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index 5d4992c10..7b01e0b2f 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -489,6 +489,7 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
request.payload.projectId,
request.payload.path,
request.payload.label,
+ request.payload.kind,
),
);
case "document.removeAsset":
diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.ts
index 0fbbccc9c..90088781a 100644
--- a/electron/native-bridge/services/aiEditionService.ts
+++ b/electron/native-bridge/services/aiEditionService.ts
@@ -151,9 +151,17 @@ export class AiEditionService {
}
}
- async addAsset(projectId: string, path: string, label?: string): Promise<AiEditionAssetResult> {
- const document = await this.options.documents.addAsset(projectId, { path, label });
- const assetId = document.project.primaryAssetId ?? document.assets.at(-1)?.id ?? "";
+ async addAsset(
+ projectId: string,
+ path: string,
+ label?: string,
+ kind?: "video" | "audio",
+ ): Promise<AiEditionAssetResult> {
+ const document = await this.options.documents.addAsset(projectId, { path, label, kind });
+ // The just-added asset is always the last one; primaryAssetId is only a
+ // fallback for the video case and would point at the wrong asset for an
+ // audio import (which never claims primary), so prefer the tail.
+ const assetId = document.assets.at(-1)?.id ?? document.project.primaryAssetId ?? "";
return { assetId, document };
}
diff --git a/electron/preload.ts b/electron/preload.ts
index 6aff16407..16227f110 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -276,6 +276,9 @@ contextBridge.exposeInMainWorld("electronAPI", {
openVideoFilePicker: () => {
return ipcRenderer.invoke("open-video-file-picker");
},
+ openAudioFilePicker: () => {
+ return ipcRenderer.invoke("open-audio-file-picker");
+ },
setCurrentVideoPath: (path: string) => {
return ipcRenderer.invoke("set-current-video-path", path);
},
diff --git a/src/i18n/locales/ar/dialogs.json b/src/i18n/locales/ar/dialogs.json
index 43caf5938..1032d22cb 100644
--- a/src/i18n/locales/ar/dialogs.json
+++ b/src/i18n/locales/ar/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "حفظ GIF المصدر",
"saveVideo": "حفظ الفيديو المصدر",
"selectVideo": "حدد ملف فيديو",
+ "selectAudio": "Select Audio File",
"saveProject": "حفظ مشروع OpenScreen",
"openProject": "فتح مشروع OpenScreen",
"gifImage": "صورة GIF",
"mp4Video": "فيديو MP4",
"videoFiles": "ملفات فيديو",
+ "audioFiles": "Audio Files",
"openscreenProject": "مشروع OpenScreen",
"allFiles": "جميع الملفات"
}
diff --git a/src/i18n/locales/en/dialogs.json b/src/i18n/locales/en/dialogs.json
index 90599af16..3d898d1a2 100644
--- a/src/i18n/locales/en/dialogs.json
+++ b/src/i18n/locales/en/dialogs.json
@@ -80,11 +80,13 @@
"saveGif": "Save Exported GIF",
"saveVideo": "Save Exported Video",
"selectVideo": "Select Video File",
+ "selectAudio": "Select Audio File",
"saveProject": "Save OpenScreen Project",
"openProject": "Open OpenScreen Project",
"gifImage": "GIF Image",
"mp4Video": "MP4 Video",
"videoFiles": "Video Files",
+ "audioFiles": "Audio Files",
"openscreenProject": "OpenScreen Project",
"allFiles": "All Files"
}
diff --git a/src/i18n/locales/es/dialogs.json b/src/i18n/locales/es/dialogs.json
index 954121938..10ebb2315 100644
--- a/src/i18n/locales/es/dialogs.json
+++ b/src/i18n/locales/es/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "Guardar GIF exportado",
"saveVideo": "Guardar video exportado",
"selectVideo": "Seleccionar archivo de video",
+ "selectAudio": "Select Audio File",
"saveProject": "Guardar proyecto OpenScreen",
"openProject": "Abrir proyecto OpenScreen",
"gifImage": "Imagen GIF",
"mp4Video": "Video MP4",
"videoFiles": "Archivos de video",
+ "audioFiles": "Audio Files",
"openscreenProject": "Proyecto OpenScreen",
"allFiles": "Todos los archivos"
}
diff --git a/src/i18n/locales/fr/dialogs.json b/src/i18n/locales/fr/dialogs.json
index 82fc95dcb..a7691550e 100644
--- a/src/i18n/locales/fr/dialogs.json
+++ b/src/i18n/locales/fr/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "Enregistrer le GIF exporté",
"saveVideo": "Enregistrer la vidéo exportée",
"selectVideo": "Sélectionner un fichier vidéo",
+ "selectAudio": "Select Audio File",
"saveProject": "Enregistrer le projet OpenScreen",
"openProject": "Ouvrir un projet OpenScreen",
"gifImage": "Image GIF",
"mp4Video": "Vidéo MP4",
"videoFiles": "Fichiers vidéo",
+ "audioFiles": "Audio Files",
"openscreenProject": "Projet OpenScreen",
"allFiles": "Tous les fichiers"
}
diff --git a/src/i18n/locales/it/dialogs.json b/src/i18n/locales/it/dialogs.json
index 0fad7d36e..b26a83da9 100644
--- a/src/i18n/locales/it/dialogs.json
+++ b/src/i18n/locales/it/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "Salva GIF esportata",
"saveVideo": "Salva video esportato",
"selectVideo": "Seleziona file video",
+ "selectAudio": "Select Audio File",
"saveProject": "Salva progetto OpenScreen",
"openProject": "Apri progetto OpenScreen",
"gifImage": "Immagine GIF",
"mp4Video": "Video MP4",
"videoFiles": "File video",
+ "audioFiles": "Audio Files",
"openscreenProject": "Progetto OpenScreen",
"allFiles": "Tutti i file"
}
diff --git a/src/i18n/locales/ja-JP/dialogs.json b/src/i18n/locales/ja-JP/dialogs.json
index 7ee976a77..911c2ad94 100644
--- a/src/i18n/locales/ja-JP/dialogs.json
+++ b/src/i18n/locales/ja-JP/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "エクスポートしたGIFを保存",
"saveVideo": "エクスポートした動画を保存",
"selectVideo": "動画ファイルを選択",
+ "selectAudio": "Select Audio File",
"saveProject": "OpenScreen プロジェクトを保存",
"openProject": "OpenScreen プロジェクトを開く",
"gifImage": "GIF 画像",
"mp4Video": "MP4 動画",
"videoFiles": "動画ファイル",
+ "audioFiles": "Audio Files",
"openscreenProject": "OpenScreen プロジェクト",
"allFiles": "すべてのファイル"
}
diff --git a/src/i18n/locales/ko-KR/dialogs.json b/src/i18n/locales/ko-KR/dialogs.json
index 5891f44c1..d654a5f52 100644
--- a/src/i18n/locales/ko-KR/dialogs.json
+++ b/src/i18n/locales/ko-KR/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "내보낸 GIF 저장",
"saveVideo": "내보낸 비디오 저장",
"selectVideo": "비디오 파일 선택",
+ "selectAudio": "Select Audio File",
"saveProject": "OpenScreen 프로젝트 저장",
"openProject": "OpenScreen 프로젝트 열기",
"gifImage": "GIF 이미지",
"mp4Video": "MP4 비디오",
"videoFiles": "비디오 파일",
+ "audioFiles": "Audio Files",
"openscreenProject": "OpenScreen 프로젝트",
"allFiles": "모든 파일"
}
diff --git a/src/i18n/locales/pt-BR/dialogs.json b/src/i18n/locales/pt-BR/dialogs.json
index ba77d90a9..7dbb4c642 100644
--- a/src/i18n/locales/pt-BR/dialogs.json
+++ b/src/i18n/locales/pt-BR/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "Salvar GIF Exportado",
"saveVideo": "Salvar Vídeo Exportado",
"selectVideo": "Selecionar Arquivo de Vídeo",
+ "selectAudio": "Select Audio File",
"saveProject": "Salvar Projeto OpenScreen",
"openProject": "Abrir Projeto OpenScreen",
"gifImage": "Imagem GIF",
"mp4Video": "Vídeo MP4",
"videoFiles": "Arquivos de Vídeo",
+ "audioFiles": "Audio Files",
"openscreenProject": "Projeto OpenScreen",
"allFiles": "Todos os Arquivos"
}
diff --git a/src/i18n/locales/ru/dialogs.json b/src/i18n/locales/ru/dialogs.json
index a821771e9..7e1dbaeed 100644
--- a/src/i18n/locales/ru/dialogs.json
+++ b/src/i18n/locales/ru/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "Сохранить экспортированный GIF",
"saveVideo": "Сохранить экспортированное видео",
"selectVideo": "Выбрать видеофайл",
+ "selectAudio": "Select Audio File",
"saveProject": "Сохранить проект OpenScreen",
"openProject": "Открыть проект OpenScreen",
"gifImage": "GIF изображение",
"mp4Video": "MP4 видео",
"videoFiles": "Видеофайлы",
+ "audioFiles": "Audio Files",
"openscreenProject": "Проект OpenScreen",
"allFiles": "Все файлы"
}
diff --git a/src/i18n/locales/tr/dialogs.json b/src/i18n/locales/tr/dialogs.json
index 196807fd3..c6299d520 100644
--- a/src/i18n/locales/tr/dialogs.json
+++ b/src/i18n/locales/tr/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "Dışa Aktarılan GIF'i Kaydet",
"saveVideo": "Dışa Aktarılan Videoyu Kaydet",
"selectVideo": "Video Dosyası Seç",
+ "selectAudio": "Select Audio File",
"saveProject": "OpenScreen Projesini Kaydet",
"openProject": "OpenScreen Projesini Aç",
"gifImage": "GIF Görüntüsü",
"mp4Video": "MP4 Video",
"videoFiles": "Video Dosyaları",
+ "audioFiles": "Audio Files",
"openscreenProject": "OpenScreen Projesi",
"allFiles": "Tüm Dosyalar"
}
diff --git a/src/i18n/locales/vi/dialogs.json b/src/i18n/locales/vi/dialogs.json
index 644d2ba02..213240763 100644
--- a/src/i18n/locales/vi/dialogs.json
+++ b/src/i18n/locales/vi/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "Lưu GIF đã xuất",
"saveVideo": "Lưu Video đã xuất",
"selectVideo": "Chọn tệp video",
+ "selectAudio": "Select Audio File",
"saveProject": "Lưu dự án OpenScreen",
"openProject": "Mở dự án OpenScreen",
"gifImage": "Hình ảnh GIF",
"mp4Video": "Video MP4",
"videoFiles": "Tệp Video",
+ "audioFiles": "Audio Files",
"openscreenProject": "Dự án OpenScreen",
"allFiles": "Tất cả các tệp"
}
diff --git a/src/i18n/locales/zh-CN/dialogs.json b/src/i18n/locales/zh-CN/dialogs.json
index 645ebf9d8..b28304f6c 100644
--- a/src/i18n/locales/zh-CN/dialogs.json
+++ b/src/i18n/locales/zh-CN/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "保存导出的 GIF",
"saveVideo": "保存导出的视频",
"selectVideo": "选择视频文件",
+ "selectAudio": "Select Audio File",
"saveProject": "保存 OpenScreen 项目",
"openProject": "打开 OpenScreen 项目",
"gifImage": "GIF 图片",
"mp4Video": "MP4 视频",
"videoFiles": "视频文件",
+ "audioFiles": "Audio Files",
"openscreenProject": "OpenScreen 项目",
"allFiles": "所有文件"
}
diff --git a/src/i18n/locales/zh-TW/dialogs.json b/src/i18n/locales/zh-TW/dialogs.json
index 14fc364a0..6c3601511 100644
--- a/src/i18n/locales/zh-TW/dialogs.json
+++ b/src/i18n/locales/zh-TW/dialogs.json
@@ -79,11 +79,13 @@
"saveGif": "儲存匯出的 GIF",
"saveVideo": "儲存匯出的影片",
"selectVideo": "選擇影片檔案",
+ "selectAudio": "Select Audio File",
"saveProject": "儲存 OpenScreen 專案",
"openProject": "開啟 OpenScreen 專案",
"gifImage": "GIF 圖片",
"mp4Video": "MP4 影片",
"videoFiles": "影片檔案",
+ "audioFiles": "Audio Files",
"openscreenProject": "OpenScreen 專案",
"allFiles": "所有檔案"
}
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index 1995b5823..b55ef79fc 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -843,6 +843,10 @@ export const createProjectInputSchema = z.object({
export const addAssetInputSchema = z.object({
path: z.string().trim().min(1),
label: z.string().trim().optional(),
+ // "audio" imports an external voiceover / BGM / SFX file (issue #350); it has
+ // no video stream and never becomes the project's primary asset. Defaults to
+ // "video" so every existing caller keeps its current behaviour.
+ kind: z.enum(["video", "audio"]).default("video"),
autoTranscribe: z.boolean().default(true),
});
diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.ts
index 84074aad2..0c920be7a 100644
--- a/src/lib/ai-edition/store/projectStore.test.ts
+++ b/src/lib/ai-edition/store/projectStore.test.ts
@@ -16,6 +16,17 @@ const toastMocks = vi.hoisted(() => ({
error: vi.fn(),
}));
+// Stub only the audio duration probe (issue #350): mounting a real <audio> in
+// jsdom never fires loadedmetadata, so an unmocked probe would block on its
+// timeout. Everything else in the module (probeVideoDimensions) stays real so
+// the video-import tests above are untouched.
+const durationMocks = vi.hoisted(() => ({ probeAudioDuration: vi.fn() }));
+
+vi.mock("../timeline/duration", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../timeline/duration")>()),
+ probeAudioDuration: durationMocks.probeAudioDuration,
+}));
+
vi.mock("@/native/client", () => ({
nativeBridgeClient: {
aiEdition: {
@@ -73,6 +84,7 @@ describe("useProjectStore", () => {
mock.mockReset();
}
toastMocks.error.mockReset();
+ durationMocks.probeAudioDuration.mockReset();
// biome-ignore lint/suspicious/noExplicitAny: test-only stub of the legacy contextBridge surface
(window as any).electronAPI = { findRecordingCamera: vi.fn() };
});
@@ -299,6 +311,69 @@ describe("useProjectStore", () => {
expect(toastMocks.error.mock.calls[0][0]).toContain("video.mp4");
});
+ // Issue #350 — external audio import.
+ it("addAudioAsset passes kind 'audio', skips the camera lookup, and returns the asset", async () => {
+ useProjectStore.setState({
+ projectId: "proj_test",
+ document: sampleDoc,
+ revision: 1,
+ status: "ready",
+ error: null,
+ });
+ durationMocks.probeAudioDuration.mockResolvedValue(null);
+ const audioDoc = {
+ ...sampleDoc,
+ assets: [
+ { id: "audio_asset", kind: "audio", label: "voiceover.mp3", originalPath: "/tmp/vo.mp3" },
+ ],
+ };
+ bridgeMocks.addAsset.mockResolvedValue({ assetId: "audio_asset", document: audioDoc });
+
+ const asset = await useProjectStore.getState().addAudioAsset("/tmp/vo.mp3");
+
+ expect(asset?.id).toBe("audio_asset");
+ expect(asset?.kind).toBe("audio");
+ // The bridge must be told this is an audio import (4th arg).
+ expect(bridgeMocks.addAsset).toHaveBeenCalledWith(
+ "proj_test",
+ "/tmp/vo.mp3",
+ undefined,
+ "audio",
+ );
+ // Audio has no camera sidecar — the lookup that addAsset does must not run.
+ // biome-ignore lint/suspicious/noExplicitAny: test-only stub of the legacy contextBridge surface
+ expect((window as any).electronAPI.findRecordingCamera).not.toHaveBeenCalled();
+ // Probe returned null, so nothing to stamp: no extra save.
+ expect(bridgeMocks.save).not.toHaveBeenCalled();
+ });
+
+ it("addAudioAsset stamps the probed duration onto the asset", async () => {
+ useProjectStore.setState({
+ projectId: "proj_test",
+ document: sampleDoc,
+ revision: 1,
+ status: "ready",
+ error: null,
+ });
+ durationMocks.probeAudioDuration.mockResolvedValue(8.25);
+ const audioDoc = {
+ ...sampleDoc,
+ assets: [
+ { id: "audio_asset", kind: "audio", label: "bgm.wav", originalPath: "/tmp/bgm.wav" },
+ ],
+ };
+ bridgeMocks.addAsset.mockResolvedValue({ assetId: "audio_asset", document: audioDoc });
+ bridgeMocks.save.mockImplementation((document: unknown) =>
+ Promise.resolve({ success: true, document }),
+ );
+
+ const asset = await useProjectStore.getState().addAudioAsset("/tmp/bgm.wav");
+
+ expect(asset?.durationSec).toBe(8.25);
+ expect(bridgeMocks.save).toHaveBeenCalledTimes(1);
+ expect(useProjectStore.getState().document?.assets[0]?.durationSec).toBe(8.25);
+ });
+
// The save boundary. Every write in the app funnels through `saveDocument`, and
// almost every caller `void`s it from a click handler, so what this function does
// with a failure IS what the user sees.
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index 48dad73e2..4d2eeb30c 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -5,7 +5,7 @@ import { toastText } from "@/i18n/toastText";
import { nativeBridgeClient } from "@/native/client";
import { type Interval, replaceTimeline as replaceTimelineOp } from "../document/timeline";
import { type AxcutAsset, type AxcutDocument, documentSchema } from "../schema";
-import { probeVideoDimensions } from "../timeline/duration";
+import { probeAudioDuration, probeVideoDimensions } from "../timeline/duration";
import { clearHistory, currentWriteEpoch, pushHistory } from "./undoStack";
// ponytail: thin Zustand wrapper over the native-bridge client. Keeps the
@@ -72,6 +72,14 @@ export interface ProjectState {
createProject: (title: string) => Promise<AxcutDocument>;
refresh: () => Promise<void>;
addAsset: (path: string, label?: string) => Promise<AxcutAsset | null>;
+ /**
+ * Import an external audio file (voiceover / BGM / SFX) as a `kind: "audio"`
+ * asset — issue #350. Unlike {@link addAsset} it never looks for a camera
+ * sidecar, and it probes the file's duration up front so the timeline can lay
+ * out its track (added separately, see the timeline store). Returns the added
+ * asset, or null if the write was superseded.
+ */
+ addAudioAsset: (path: string, label?: string) => Promise<AxcutAsset | null>;
removeAsset: (assetId: string) => Promise<void>;
/**
* Write the document to disk. Resolves `true` when it took effect, `false` when it
@@ -325,6 +333,51 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
return addedAsset;
},
+ async addAudioAsset(path, label) {
+ const { projectId } = get();
+ if (!projectId) throw new Error("No project loaded");
+ // Same superseded guard as addAsset: the native add, a duration probe and a
+ // save all await, and a project switch / clear can land in between.
+ const epoch = currentWriteEpoch();
+ const superseded = () => get().projectId !== projectId || currentWriteEpoch() !== epoch;
+ const result = await nativeBridgeClient.aiEdition.addAsset(projectId, path, label, "audio");
+ if (superseded()) return null;
+ let document = parseDocument(result.document);
+ const addedAsset =
+ document.assets.find(
+ (a) => a.kind === "audio" && a.originalPath === path && (label ? a.label === label : true),
+ ) ??
+ document.assets.at(-1) ??
+ null;
+ if (!addedAsset) return null;
+
+ // Probe the real length so the timeline can size the track pill immediately
+ // on add. Non-fatal: an unreadable file just leaves durationSec unset and the
+ // track store falls back to a placeholder. No camera lookup — audio has none.
+ const durationSec = await probeAudioDuration(toFileUrl(addedAsset.originalPath)).catch(
+ () => null,
+ );
+ if (superseded()) return null;
+ if (durationSec != null) {
+ const next: AxcutDocument = {
+ ...document,
+ assets: document.assets.map((a) => (a.id === addedAsset.id ? { ...a, durationSec } : a)),
+ };
+ // history: false — probing a duration is part of the import, not an edit
+ // of its own, so it must not become the thing the next Ctrl+Z reverses.
+ if (await get().saveDocument(next, { history: false })) document = parseDocument(next);
+ }
+
+ if (superseded()) return null;
+ set({
+ document,
+ revision: get().revision + 1,
+ dirty: false,
+ lastSavedAt: new Date(),
+ });
+ return document.assets.find((a) => a.id === addedAsset.id) ?? addedAsset;
+ },
+
async removeAsset(assetId) {
const { projectId } = get();
if (!projectId) throw new Error("No project loaded");
diff --git a/src/lib/ai-edition/timeline/duration.test.ts b/src/lib/ai-edition/timeline/duration.test.ts
index 528c3b910..ccc41cb5a 100644
--- a/src/lib/ai-edition/timeline/duration.test.ts
+++ b/src/lib/ai-edition/timeline/duration.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { probeVideoDuration } from "./duration";
+import { probeAudioDuration, probeVideoDuration } from "./duration";
interface FakeVideo {
duration: number;
@@ -8,7 +8,16 @@ interface FakeVideo {
onerror: ((ev: Event) => unknown) | null;
}
-describe("probeVideoDuration", () => {
+// `probeVideoDuration` and `probeAudioDuration` are the same probe on a
+// different media element, so the fake-element harness and the cases are shared
+// and driven per tag. See the schema/store for why audio import needs its own
+// probe (issue #350).
+const PROBES = [
+ { label: "probeVideoDuration", tag: "video", probe: probeVideoDuration },
+ { label: "probeAudioDuration", tag: "audio", probe: probeAudioDuration },
+] as const;
+
+describe.each(PROBES)("$label", ({ tag, probe }) => {
let created: FakeVideo[];
let originalCreate: typeof document.createElement;
let appendSpy: ReturnType<typeof vi.spyOn> | null;
@@ -21,9 +30,9 @@ describe("probeVideoDuration", () => {
// `"webview"`-only overload — the one `.call` resolves to, which then rejects a
// generic string tag. Pin the plain `(tagName: string) => HTMLElement` overload.
const createReal: (this: Document, tag: string) => HTMLElement = originalCreate;
- document.createElement = ((tag: string) => {
- const node = createReal.call(document, tag);
- if (tag === "video") {
+ document.createElement = ((el: string) => {
+ const node = createReal.call(document, el);
+ if (el === tag) {
const fake: FakeVideo = {
duration: Number.NaN,
onloadedmetadata: null,
@@ -66,11 +75,11 @@ describe("probeVideoDuration", () => {
});
it("returns null when src is empty", async () => {
- await expect(probeVideoDuration("")).resolves.toBeNull();
+ await expect(probe("")).resolves.toBeNull();
});
it("returns duration on loadedmetadata", async () => {
- const p = probeVideoDuration("file:///tmp/clip.mp4");
+ const p = probe("file:///tmp/clip");
await vi.advanceTimersByTimeAsync(0);
const v = created[0];
v.duration = 12.5;
@@ -79,14 +88,14 @@ describe("probeVideoDuration", () => {
});
it("returns null on error", async () => {
- const p = probeVideoDuration("file:///missing.mp4");
+ const p = probe("file:///missing");
await vi.advanceTimersByTimeAsync(0);
created[0].onerror?.(new Event("error"));
await expect(p).resolves.toBeNull();
});
it("returns null on timeout", async () => {
- const p = probeVideoDuration("file:///slow.mp4", 1000);
+ const p = probe("file:///slow", 1000);
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(2000);
await expect(p).resolves.toBeNull();
@@ -94,7 +103,7 @@ describe("probeVideoDuration", () => {
it("returns null for non-finite duration", async () => {
for (const d of [Number.POSITIVE_INFINITY, Number.NaN, -1, 0]) {
- const p = probeVideoDuration("file:///x.mp4");
+ const p = probe("file:///x");
await vi.advanceTimersByTimeAsync(0);
const v = created[created.length - 1];
v.duration = d;
diff --git a/src/lib/ai-edition/timeline/duration.ts b/src/lib/ai-edition/timeline/duration.ts
index 950d2ae3b..87d01ab11 100644
--- a/src/lib/ai-edition/timeline/duration.ts
+++ b/src/lib/ai-edition/timeline/duration.ts
@@ -62,6 +62,64 @@ export function probeVideoDuration(
});
}
+/**
+ * Duration of an imported audio file (issue #350), probed by mounting a hidden
+ * <audio> and waiting for loadedmetadata — the audio-only counterpart of
+ * `probeVideoDuration`. Used when an external voiceover / BGM / SFX file is added
+ * so the timeline can size its track pill at the real length immediately.
+ *
+ * Falls back to null on error / timeout / non-finite duration, exactly like the
+ * video probe; the caller decides whether to retry or use a placeholder.
+ */
+export function probeAudioDuration(
+ src: string,
+ timeoutMs: number = DEFAULT_TIMEOUT_MS,
+): Promise<number | null> {
+ return new Promise((resolve) => {
+ if (typeof document === "undefined" || !src) {
+ resolve(null);
+ return;
+ }
+ const audio = document.createElement("audio");
+ audio.preload = "metadata";
+ audio.style.position = "absolute";
+ audio.style.width = "1px";
+ audio.style.height = "1px";
+ audio.style.opacity = "0";
+ audio.style.pointerEvents = "none";
+ audio.style.left = "-9999px";
+ let settled = false;
+ const cleanup = () => {
+ audio.onloadedmetadata = null;
+ audio.onerror = null;
+ clearTimeout(timer);
+ try {
+ audio.removeAttribute("src");
+ audio.load();
+ } catch {
+ // ignore — browser may refuse if already detached
+ }
+ if (audio.parentNode) audio.parentNode.removeChild(audio);
+ };
+ const settle = (value: number | null) => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ resolve(value);
+ };
+ const timer = setTimeout(() => settle(null), timeoutMs);
+ audio.onloadedmetadata = () => {
+ const d = audio.duration;
+ settle(Number.isFinite(d) && d > 0 ? d : null);
+ };
+ audio.onerror = () => settle(null);
+ // Append to body so some browsers (Firefox) fire loadedmetadata for an
+ // otherwise-detached media element — same reason as the video probe.
+ document.body.appendChild(audio);
+ audio.src = src;
+ });
+}
+
/** Native pixel dimensions, same probe shape as `probeVideoDuration` (separate DOM element —
* cheap, one-shot, not worth merging into a combined probe for the one extra caller that
* needs both). `asset.video` was otherwise left permanently unset for most recordings (nothing
diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts
index c00f53d51..c9e5d395b 100644
--- a/src/native/browserShim.ts
+++ b/src/native/browserShim.ts
@@ -186,7 +186,7 @@ function createShimBridgeClient() {
updatedAt: string;
primaryAssetId?: string;
};
- assets: Array<{ id: string; kind: "video"; label: string; originalPath: string }>;
+ assets: Array<{ id: string; kind: "video" | "audio"; label: string; originalPath: string }>;
[key: string]: unknown;
};
const projectsStorageKey = "browser-shim-projects-v2";
@@ -408,20 +408,27 @@ function createShimBridgeClient() {
saveProjectsState();
return Promise.resolve({ success: true });
},
- addAsset: (projectId: string, path: string, label?: string) => {
+ addAsset: (projectId: string, path: string, label?: string, kind?: "video" | "audio") => {
const doc = documentsByProject[projectId];
if (!doc) return Promise.resolve({ assetId: "", document: null });
const assetId = `asset_${Math.random().toString(36).slice(2, 10)}`;
+ const assetKind = kind ?? "video";
const asset = {
id: assetId,
- kind: "video" as const,
+ kind: assetKind,
label: label || path.split(/[\\/]/).pop() || "Recording",
originalPath: path,
};
+ // Mirror the main-process rule: an audio import never claims the empty
+ // primary slot (see document-service.addAsset).
+ const claimsPrimary = assetKind !== "audio" && !doc.project.primaryAssetId;
const next: ShimDocument = {
...doc,
assets: [...doc.assets, asset],
- project: { ...doc.project, primaryAssetId: doc.project.primaryAssetId ?? assetId },
+ project: {
+ ...doc.project,
+ primaryAssetId: claimsPrimary ? assetId : doc.project.primaryAssetId,
+ },
};
documentsByProject[projectId] = next;
saveProjectsState();
diff --git a/src/native/client.ts b/src/native/client.ts
index eed5d68d7..fce40fa6c 100644
--- a/src/native/client.ts
+++ b/src/native/client.ts
@@ -181,11 +181,11 @@ export const nativeBridgeClient = {
action: "document.delete",
payload: { projectId },
}),
- addAsset: (projectId: string, path: string, label?: string) =>
+ addAsset: (projectId: string, path: string, label?: string, kind?: "video" | "audio") =>
requireNativeBridgeData<AiEditionAssetResult>({
domain: "aiEdition",
action: "document.addAsset",
- payload: { projectId, path, label },
+ payload: { projectId, path, label, kind },
}),
removeAsset: (projectId: string, assetId: string) =>
requireNativeBridgeData<AiEditionAssetResult>({
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 7e7fc11c9..54c1cc775 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -533,7 +533,7 @@ export type NativeBridgeRequest =
| {
domain: "aiEdition";
action: "document.addAsset";
- payload: { projectId: string; path: string; label?: string };
+ payload: { projectId: string; path: string; label?: string; kind?: "video" | "audio" };
requestId?: string;
}
| {