Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat: support multiple audio tracks from imported video files

copilot-swe-agent[bot]a6339e6c630d
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 5a6de8d1..62da54dd 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -208,6 +208,83 @@ export const Preview: React.FC = () => {
);
const audioBufferCacheRef = useRef<Map<string, AudioBuffer>>(new Map());
+ /** Returns the cache key for an audio buffer, accounting for multi-track audio files. */
+ const getAudioBufferCacheKey = (mediaId: string, audioTrackIndex?: number): string =>
+ audioTrackIndex && audioTrackIndex > 0
+ ? `${mediaId}:${audioTrackIndex}`
+ : mediaId;
+
+ /**
+ * Loads an AudioBuffer for the given media item and audio track index.
+ * Uses mediabunny for non-primary tracks; falls back to decodeAudioData for the primary track.
+ */
+ const loadAudioBuffer = async (
+ audioContext: AudioContext | BaseAudioContext,
+ blob: Blob,
+ audioTrackIndex: number = 0,
+ ): Promise<AudioBuffer | null> => {
+ if (audioTrackIndex === 0) {
+ try {
+ const arrayBuffer = await blob.arrayBuffer();
+ return await audioContext.decodeAudioData(arrayBuffer);
+ } catch {
+ // Fall through to mediabunny extraction
+ }
+ }
+ // Use mediabunny to extract the specific audio track
+ try {
+ const { Input, ALL_FORMATS, BlobSource, AudioBufferSink } =
+ await import("mediabunny");
+ const input = new Input({ source: new BlobSource(blob), formats: ALL_FORMATS });
+ const audioTracks = await (input as any).getAudioTracks();
+ const track =
+ audioTracks[audioTrackIndex] ??
+ (await (input as any).getPrimaryAudioTrack()) ??
+ audioTracks[0] ??
+ null;
+ if (!track) {
+ (input as any)[Symbol.dispose]?.();
+ return null;
+ }
+ const canDecode = await track.canDecode();
+ if (!canDecode) {
+ (input as any)[Symbol.dispose]?.();
+ return null;
+ }
+ const sink = new AudioBufferSink(track);
+ const duration = await track.computeDuration();
+ if (!duration || duration <= 0) {
+ (input as any)[Symbol.dispose]?.();
+ return null;
+ }
+ // Collect all audio buffers from the sink
+ const chunks: { buffer: AudioBuffer; timestamp: number }[] = [];
+ for await (const wrapped of sink.buffers(0, duration)) {
+ chunks.push({ buffer: wrapped.buffer, timestamp: wrapped.timestamp });
+ }
+ (input as any)[Symbol.dispose]?.();
+ if (chunks.length === 0) return null;
+ // Concatenate all chunks into a single AudioBuffer
+ const sampleRate = chunks[0].buffer.sampleRate;
+ const numChannels = chunks[0].buffer.numberOfChannels;
+ const totalFrames = Math.ceil(duration * sampleRate);
+ const combined = (audioContext as AudioContext).createBuffer
+ ? (audioContext as AudioContext).createBuffer(numChannels, totalFrames, sampleRate)
+ : new OfflineAudioContext(numChannels, totalFrames, sampleRate).createBuffer(numChannels, totalFrames, sampleRate);
+ for (const chunk of chunks) {
+ const offsetFrames = Math.round(chunk.timestamp * sampleRate);
+ for (let ch = 0; ch < numChannels; ch++) {
+ const dest = combined.getChannelData(ch);
+ const src = chunk.buffer.getChannelData(ch);
+ dest.set(src, offsetFrames);
+ }
+ }
+ return combined;
+ } catch {
+ return null;
+ }
+ };
+
const rendererRef = useRef<Renderer | null>(null);
const rendererInitializedRef = useRef<boolean>(false);
@@ -852,14 +929,24 @@ export const Preview: React.FC = () => {
}
let audioBuffer = audioBufferCacheRef.current.get(
- audioClip.mediaId,
+ getAudioBufferCacheKey(audioClip.mediaId, audioClip.audioTrackIndex),
);
if (!audioBuffer) {
try {
const audioContext = audioGraph.getAudioContext();
- const arrayBuffer = await mediaItem.blob.arrayBuffer();
- audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
- audioBufferCacheRef.current.set(audioClip.mediaId, audioBuffer);
+ const loaded = await loadAudioBuffer(
+ audioContext,
+ mediaItem.blob,
+ audioClip.audioTrackIndex ?? 0,
+ );
+ if (!loaded) {
+ continue;
+ }
+ audioBuffer = loaded;
+ audioBufferCacheRef.current.set(
+ getAudioBufferCacheKey(audioClip.mediaId, audioClip.audioTrackIndex),
+ audioBuffer,
+ );
} catch (error) {
console.warn(
`[Preview] Failed to decode audio for clip ${audioClip.id}:`,
@@ -947,7 +1034,8 @@ export const Preview: React.FC = () => {
for (const track of allTracks) {
for (const clip of track.clips) {
- if (audioBufferCacheRef.current.has(clip.mediaId)) {
+ const cacheKey = getAudioBufferCacheKey(clip.mediaId, clip.audioTrackIndex);
+ if (audioBufferCacheRef.current.has(cacheKey)) {
continue;
}
@@ -957,9 +1045,14 @@ export const Preview: React.FC = () => {
}
try {
- const arrayBuffer = await mediaItem.blob.arrayBuffer();
- const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
- audioBufferCacheRef.current.set(clip.mediaId, audioBuffer);
+ const audioBuffer = await loadAudioBuffer(
+ audioContext,
+ mediaItem.blob,
+ clip.audioTrackIndex ?? 0,
+ );
+ if (audioBuffer) {
+ audioBufferCacheRef.current.set(cacheKey, audioBuffer);
+ }
} catch {
}
}
@@ -982,7 +1075,9 @@ export const Preview: React.FC = () => {
continue;
}
- const audioBuffer = audioBufferCacheRef.current.get(clip.mediaId);
+ const audioBuffer = audioBufferCacheRef.current.get(
+ getAudioBufferCacheKey(clip.mediaId, clip.audioTrackIndex),
+ );
if (!audioBuffer) {
continue;
}
@@ -1940,7 +2035,9 @@ export const Preview: React.FC = () => {
mediaItem.metadata.channels > 0);
if (!hasAudio) continue;
- const audioBuffer = audioBufferCacheRef.current.get(audioClip.mediaId);
+ const audioBuffer = audioBufferCacheRef.current.get(
+ getAudioBufferCacheKey(audioClip.mediaId, audioClip.audioTrackIndex),
+ );
if (audioBuffer) {
schedules.push({
clipId: audioClip.id,
diff --git a/apps/web/src/stores/project-store.test.ts b/apps/web/src/stores/project-store.test.ts
index 28f1d7dd..4972b02e 100644
--- a/apps/web/src/stores/project-store.test.ts
+++ b/apps/web/src/stores/project-store.test.ts
@@ -609,6 +609,132 @@ describe("ProjectStore", () => {
expect(useProjectStore.getState().clipboard.length).toBe(1);
});
});
+
+ describe("separateAudio", () => {
+ const createProjectWithVideoClip = (audioTrackCount?: number): Project => {
+ const mediaItem: MediaItem = {
+ id: "video-media-1",
+ name: "multi-audio.mp4",
+ type: "video",
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 10,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48000,
+ channels: 2,
+ fileSize: 1000000,
+ audioTrackCount,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ };
+
+ const videoClip: Clip = {
+ id: "video-clip-1",
+ mediaId: "video-media-1",
+ trackId: "video-track-1",
+ startTime: 0,
+ duration: 10,
+ inPoint: 0,
+ outPoint: 10,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0.5, y: 0.5 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ };
+
+ return {
+ id: "test-project",
+ name: "Test",
+ createdAt: Date.now(),
+ modifiedAt: Date.now(),
+ settings: {
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ sampleRate: 48000,
+ channels: 2,
+ },
+ mediaLibrary: { items: [mediaItem] },
+ timeline: {
+ tracks: [
+ {
+ id: "video-track-1",
+ type: "video",
+ name: "Video",
+ clips: [videoClip],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ ],
+ subtitles: [],
+ duration: 10,
+ markers: [],
+ },
+ };
+ };
+
+ it("should create one audio clip when media has a single audio track", async () => {
+ useProjectStore.getState().loadProject(createProjectWithVideoClip(1));
+ const result = await useProjectStore.getState().separateAudio("video-clip-1");
+
+ expect(result.success).toBe(true);
+ const { project } = useProjectStore.getState();
+ const audioTracks = project.timeline.tracks.filter((t) => t.type === "audio");
+ expect(audioTracks.length).toBe(1);
+ expect(audioTracks[0].clips.length).toBe(1);
+ expect(audioTracks[0].clips[0].mediaId).toBe("video-media-1");
+ });
+
+ it("should create multiple audio clips when media has multiple audio tracks", async () => {
+ useProjectStore.getState().loadProject(createProjectWithVideoClip(3));
+ const result = await useProjectStore.getState().separateAudio("video-clip-1");
+
+ expect(result.success).toBe(true);
+ const { project } = useProjectStore.getState();
+ const audioTracks = project.timeline.tracks.filter((t) => t.type === "audio");
+ expect(audioTracks.length).toBe(3);
+
+ // Each audio track should have one clip with the correct audioTrackIndex
+ for (let i = 0; i < 3; i++) {
+ expect(audioTracks[i].clips.length).toBe(1);
+ expect(audioTracks[i].clips[0].mediaId).toBe("video-media-1");
+ expect(audioTracks[i].clips[0].audioTrackIndex).toBe(i);
+ }
+ });
+
+ it("should default to one audio track when audioTrackCount is undefined", async () => {
+ useProjectStore.getState().loadProject(createProjectWithVideoClip(undefined));
+ const result = await useProjectStore.getState().separateAudio("video-clip-1");
+
+ expect(result.success).toBe(true);
+ const { project } = useProjectStore.getState();
+ const audioTracks = project.timeline.tracks.filter((t) => t.type === "audio");
+ expect(audioTracks.length).toBe(1);
+ });
+
+ it("should return an error when clip is not found", async () => {
+ useProjectStore.getState().createNewProject();
+ const result = await useProjectStore.getState().separateAudio("non-existent-clip");
+
+ expect(result.success).toBe(false);
+ expect(result.error?.code).toBe("CLIP_NOT_FOUND");
+ });
+ });
});
describe("ProjectStore - Text Clips", () => {
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index a3fec2b9..c1ca8e8b 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -1274,7 +1274,7 @@ export const useProjectStore = create<ProjectState>()(
},
separateAudio: async (clipId: string) => {
- const { project, actionExecutor, addTrack } = get();
+ const { project, actionExecutor } = get();
const videoClip = project.timeline.tracks
.flatMap((t) => t.clips)
@@ -1306,9 +1306,29 @@ export const useProjectStore = create<ProjectState>()(
};
}
- let audioTrack = project.timeline.tracks.find((t) => t.type === "audio");
- if (!audioTrack) {
- const trackResult = await addTrack("audio");
+ // Determine how many audio tracks to separate
+ const audioTrackCount = mediaItem.metadata.audioTrackCount ?? 1;
+
+ // Apply all track/add and clip/add actions on a single project copy to
+ // avoid race conditions from multiple store updates.
+ const projectCopy = structuredClone(project);
+
+ // Add new audio timeline tracks as needed (reuse existing ones)
+ const existingAudioCount = projectCopy.timeline.tracks.filter(
+ (t) => t.type === "audio",
+ ).length;
+
+ const newTrackIds: string[] = [];
+ for (let i = existingAudioCount; i < audioTrackCount; i++) {
+ const newTrackId = uuidv4();
+ newTrackIds.push(newTrackId);
+ const trackAction: Action = {
+ type: "track/add",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: { trackType: "audio", trackId: newTrackId },
+ };
+ const trackResult = await actionExecutor.execute(trackAction, projectCopy);
if (!trackResult.success) {
return {
success: false,
@@ -1318,13 +1338,14 @@ export const useProjectStore = create<ProjectState>()(
},
};
}
- const { project: updatedProject } = get();
- audioTrack = updatedProject.timeline.tracks.find(
- (t) => t.type === "audio",
- );
}
- if (!audioTrack) {
+ // Capture audio track IDs from the (now-updated) projectCopy
+ const audioTimelineTracks = projectCopy.timeline.tracks.filter(
+ (t) => t.type === "audio",
+ );
+
+ if (audioTimelineTracks.length === 0) {
return {
success: false,
error: {
@@ -1334,21 +1355,35 @@ export const useProjectStore = create<ProjectState>()(
};
}
- const projectCopy = structuredClone(get().project);
- const action: Action = {
- type: "clip/add",
- id: uuidv4(),
- timestamp: Date.now(),
- params: {
- trackId: audioTrack.id,
- mediaId: videoClip.mediaId,
- startTime: videoClip.startTime,
- },
+ // Add one clip per audio track in the source file
+ let lastResult: ActionResult = {
+ success: true,
};
- const result = await actionExecutor.execute(action, projectCopy);
+ for (let trackIdx = 0; trackIdx < audioTrackCount; trackIdx++) {
+ const targetTrack = audioTimelineTracks[trackIdx];
+ if (!targetTrack) break;
- if (result.success) {
+ const action: Action = {
+ type: "clip/add",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: {
+ trackId: targetTrack.id,
+ mediaId: videoClip.mediaId,
+ startTime: videoClip.startTime,
+ audioTrackIndex: trackIdx,
+ },
+ };
+
+ lastResult = await actionExecutor.execute(action, projectCopy);
+
+ if (!lastResult.success) {
+ break;
+ }
+ }
+
+ if (lastResult.success) {
const finalProject: Project = {
...projectCopy,
modifiedAt: Date.now(),
@@ -1356,7 +1391,7 @@ export const useProjectStore = create<ProjectState>()(
set({ project: finalProject });
}
- return result;
+ return lastResult;
},
removeClip: async (clipId: string) => {
diff --git a/packages/core/src/actions/action-executor.ts b/packages/core/src/actions/action-executor.ts
index 79f36ff3..ccb5c561 100644
--- a/packages/core/src/actions/action-executor.ts
+++ b/packages/core/src/actions/action-executor.ts
@@ -339,6 +339,7 @@ export class ActionExecutor {
const params = action.params as {
trackType: string;
position?: number;
+ trackId?: string;
};
const trackNames: Record<string, string> = {
video: "Video",
@@ -352,7 +353,7 @@ export class ActionExecutor {
(t: MutableTrack) => t.type === params.trackType,
).length + 1;
const newTrack: MutableTrack = {
- id: `track-${Date.now()}`,
+ id: params.trackId ?? `track-${Date.now()}`,
type: params.trackType as Track["type"],
name: `${trackNames[params.trackType] || params.trackType} ${trackCount}`,
clips: [],
@@ -457,6 +458,7 @@ export class ActionExecutor {
mediaId: string;
startTime: number;
duration?: number;
+ audioTrackIndex?: number;
};
const track = timeline.tracks.find(
(t: MutableTrack) => t.id === params.trackId,
@@ -491,6 +493,9 @@ export class ActionExecutor {
},
volume: 1,
keyframes: [],
+ ...(params.audioTrackIndex !== undefined
+ ? { audioTrackIndex: params.audioTrackIndex }
+ : {}),
};
track.clips = [...track.clips, newClip];
this.lastAddedIds.set("clip", newClip.id);
diff --git a/packages/core/src/audio/audio-engine.ts b/packages/core/src/audio/audio-engine.ts
index 96385b9f..364d47dd 100644
--- a/packages/core/src/audio/audio-engine.ts
+++ b/packages/core/src/audio/audio-engine.ts
@@ -24,7 +24,10 @@ class SegmentedAudioDecoder {
private sink: InstanceType<typeof import("mediabunny").AudioBufferSink> | null = null;
private initialized = false;
- constructor(private readonly file: File | Blob) {}
+ constructor(
+ private readonly file: File | Blob,
+ private readonly audioTrackIndex: number = 0,
+ ) {}
async initialize(): Promise<boolean> {
if (this.initialized) return true;
@@ -38,11 +41,12 @@ class SegmentedAudioDecoder {
formats: ALL_FORMATS,
}) as unknown as MediaBunnyAudioInput;
- let audioTrack = await this.input.getPrimaryAudioTrack();
- if (!audioTrack) {
- const audioTracks = await this.input.getAudioTracks();
- audioTrack = audioTracks[0] ?? null;
- }
+ const audioTracks = await this.input.getAudioTracks();
+ let audioTrack =
+ audioTracks[this.audioTrackIndex] ??
+ (await this.input.getPrimaryAudioTrack()) ??
+ audioTracks[0] ??
+ null;
if (!audioTrack) {
this.dispose();
@@ -335,14 +339,19 @@ export class AudioEngine {
fadeOut: clip.fade?.fadeOut,
speed: (clip as any).speed || 1,
reversed: (clip as any).reversed || false,
+ audioTrackIndex: clip.audioTrackIndex,
};
}
private async getAudioBuffer(
mediaItem: MediaItem,
context: BaseAudioContext,
+ audioTrackIndex: number = 0,
): Promise<AudioBuffer | null> {
- const cached = this.mediaBuffers.get(mediaItem.id);
+ const cacheKey = audioTrackIndex > 0
+ ? `${mediaItem.id}:${audioTrackIndex}`
+ : mediaItem.id;
+ const cached = this.mediaBuffers.get(cacheKey);
if (cached) return cached;
if (!mediaItem.blob) {
@@ -351,33 +360,38 @@ export class AudioEngine {
}
try {
- const arrayBuffer = await mediaItem.blob.arrayBuffer();
- const audioBuffer = await context.decodeAudioData(arrayBuffer);
+ if (audioTrackIndex === 0) {
+ const arrayBuffer = await mediaItem.blob.arrayBuffer();
+ const audioBuffer = await context.decodeAudioData(arrayBuffer);
+ this.mediaBuffers.set(cacheKey, audioBuffer);
+ return audioBuffer;
+ }
+ } catch {
+ // Fall through to mediabunny extraction
+ }
- this.mediaBuffers.set(mediaItem.id, audioBuffer);
- return audioBuffer;
- } catch (error) {
- if (mediaItem.type === "video") {
- try {
- const audioBuffer = await this.extractAudioFromVideo(
- mediaItem,
- context,
- );
- if (audioBuffer) {
- this.mediaBuffers.set(mediaItem.id, audioBuffer);
- return audioBuffer;
- }
- } catch (videoError) {
- // Video audio extraction failed
+ if (mediaItem.type === "video" || audioTrackIndex > 0) {
+ try {
+ const audioBuffer = await this.extractAudioFromVideo(
+ mediaItem,
+ context,
+ audioTrackIndex,
+ );
+ if (audioBuffer) {
+ this.mediaBuffers.set(cacheKey, audioBuffer);
+ return audioBuffer;
}
+ } catch {
+ // Video audio extraction failed
}
- return null;
}
+ return null;
}
private async extractAudioFromVideo(
mediaItem: MediaItem,
context: BaseAudioContext,
+ audioTrackIndex: number = 0,
): Promise<AudioBuffer | null> {
if (!mediaItem.blob) return null;
@@ -390,18 +404,12 @@ export class AudioEngine {
formats: ALL_FORMATS,
});
- let audioTrack = await input.getPrimaryAudioTrack();
- if (!audioTrack) {
- const audioTracks = await input.getAudioTracks();
- if (audioTracks.length > 0) {
- audioTrack = audioTracks[0];
- }
- }
-
- if (!audioTrack) {
- input[Symbol.dispose]?.();
- return null;
- }
+ const audioTracks = await input.getAudioTracks();
+ let audioTrack =
+ audioTracks[audioTrackIndex] ??
+ (await input.getPrimaryAudioTrack()) ??
+ audioTracks[0] ??
+ null;
const canDecode = await audioTrack.canDecode();
if (!canDecode) {
@@ -499,7 +507,7 @@ export class AudioEngine {
}
}
- const audioBuffer = await this.getAudioBuffer(mediaItem, context);
+ const audioBuffer = await this.getAudioBuffer(mediaItem, context, clipInfo.audioTrackIndex ?? 0);
if (!audioBuffer) {
return;
}
@@ -544,7 +552,7 @@ export class AudioEngine {
clipInfo: AudioClipRenderInfo,
renderStartTime: number,
): Promise<boolean> {
- const decoder = await this.getSegmentedAudioDecoder(mediaItem);
+ const decoder = await this.getSegmentedAudioDecoder(mediaItem, clipInfo.audioTrackIndex ?? 0);
if (!decoder) {
return false;
}
@@ -609,23 +617,27 @@ export class AudioEngine {
private async getSegmentedAudioDecoder(
mediaItem: MediaItem,
+ audioTrackIndex: number = 0,
): Promise<SegmentedAudioDecoder | null> {
if (!mediaItem.blob) {
return null;
}
- const cached = this.segmentedAudioDecoders.get(mediaItem.id);
+ const cacheKey = audioTrackIndex > 0
+ ? `${mediaItem.id}:${audioTrackIndex}`
+ : mediaItem.id;
+ const cached = this.segmentedAudioDecoders.get(cacheKey);
if (cached) {
return cached;
}
- const decoder = new SegmentedAudioDecoder(mediaItem.blob);
+ const decoder = new SegmentedAudioDecoder(mediaItem.blob, audioTrackIndex);
const initialized = await decoder.initialize();
if (!initialized) {
return null;
}
- this.segmentedAudioDecoders.set(mediaItem.id, decoder);
+ this.segmentedAudioDecoders.set(cacheKey, decoder);
return decoder;
}
diff --git a/packages/core/src/audio/types.ts b/packages/core/src/audio/types.ts
index 1c081dd1..9f7b99a2 100644
--- a/packages/core/src/audio/types.ts
+++ b/packages/core/src/audio/types.ts
@@ -42,6 +42,8 @@ export interface AudioClipRenderInfo {
readonly fadeOut?: number;
readonly speed?: number;
readonly reversed?: boolean;
+ /** Zero-based index of the audio track within the source media file to use. */
+ readonly audioTrackIndex?: number;
}
export interface AudioChannelState {
diff --git a/packages/core/src/media/media-import-service.ts b/packages/core/src/media/media-import-service.ts
index 11f6a5d2..06fcf345 100644
--- a/packages/core/src/media/media-import-service.ts
+++ b/packages/core/src/media/media-import-service.ts
@@ -338,6 +338,7 @@ export class MediaImportService {
sampleRate: processedMedia.metadata.sampleRate,
channels: processedMedia.metadata.channels,
fileSize: processedMedia.metadata.fileSize,
+ audioTrackCount: processedMedia.metadata.audioTrackCount,
};
return {
diff --git a/packages/core/src/media/mediabunny-engine.ts b/packages/core/src/media/mediabunny-engine.ts
index 85bfebf9..4688878d 100644
--- a/packages/core/src/media/mediabunny-engine.ts
+++ b/packages/core/src/media/mediabunny-engine.ts
@@ -61,6 +61,7 @@ type MediaBunnyInput = {
getMimeType(): Promise<string>;
getPrimaryVideoTrack(): Promise<InputVideoTrack | null>;
getPrimaryAudioTrack(): Promise<InputAudioTrack | null>;
+ getAudioTracks(): Promise<InputAudioTrack[]>;
getFormat(): Promise<unknown>;
[Symbol.dispose]?: () => void;
};
@@ -372,6 +373,7 @@ export class MediaBunnyEngine {
let channels = 0;
let audioCodec = "";
let canDecodeAudio = false;
+ let audioTrackCount = 0;
if (audioTrack) {
sampleRate = audioTrack.sampleRate;
@@ -380,6 +382,13 @@ export class MediaBunnyEngine {
canDecodeAudio = await audioTrack.canDecode();
}
+ try {
+ const allAudioTracks = await input.getAudioTracks();
+ audioTrackCount = allAudioTracks.length;
+ } catch {
+ audioTrackCount = audioTrack ? 1 : 0;
+ }
+
return {
duration,
width,
@@ -395,6 +404,7 @@ export class MediaBunnyEngine {
rotation,
canDecode: canDecodeVideo || canDecodeAudio,
videoBitrate,
+ audioTrackCount,
};
} finally {
input[Symbol.dispose]?.();
diff --git a/packages/core/src/media/types.ts b/packages/core/src/media/types.ts
index d4ed5367..1a31c38e 100644
--- a/packages/core/src/media/types.ts
+++ b/packages/core/src/media/types.ts
@@ -24,6 +24,8 @@ export interface MediaTrackInfo {
canDecode: boolean;
videoBitrate?: number;
audioBitrate?: number;
+ /** Number of audio tracks in the file (may be > 1 for multi-track video/audio files) */
+ audioTrackCount?: number;
}
export interface ThumbnailResult {
diff --git a/packages/core/src/types/actions.ts b/packages/core/src/types/actions.ts
index 81778fe9..449649b8 100644
--- a/packages/core/src/types/actions.ts
+++ b/packages/core/src/types/actions.ts
@@ -84,6 +84,8 @@ export type TrackAction =
params: {
trackType: "video" | "audio" | "image" | "text" | "graphics";
position?: number;
+ /** Pre-assigned track ID. When omitted, the executor generates one. */
+ trackId?: string;
};
}
| { type: "track/remove"; params: { trackId: string } }
diff --git a/packages/core/src/types/project.ts b/packages/core/src/types/project.ts
index 50d99d5b..8cad1841 100644
--- a/packages/core/src/types/project.ts
+++ b/packages/core/src/types/project.ts
@@ -65,4 +65,6 @@ export interface MediaMetadata {
readonly sampleRate: number; // For audio
readonly channels: number; // For audio
readonly fileSize: number;
+ /** Number of audio tracks in the file (may be > 1 for multi-track video/audio files) */
+ readonly audioTrackCount?: number;
}
diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.ts
index 36a2801b..9c7de320 100644
--- a/packages/core/src/types/timeline.ts
+++ b/packages/core/src/types/timeline.ts
@@ -59,6 +59,9 @@ export interface Clip {
readonly speed?: number;
readonly reversed?: boolean;
readonly emphasisAnimation?: EmphasisAnimation;
+ /** Zero-based index of the audio track within the source media file to use for this clip.
+ * Undefined or 0 means the primary/first audio track. */
+ readonly audioTrackIndex?: number;
}
export interface Effect {