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

fix: properly isolate audio streams when separating tracks

Augustus Otu1b55dc6f0292
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index bf8a5c38..3e2af4dd 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -208,79 +208,33 @@ 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 !== undefined && audioTrackIndex > 0
- ? `${mediaId}:${audioTrackIndex}`
- : mediaId;
+ `${mediaId}:${audioTrackIndex ?? 0}`;
- /**
- * 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> => {
+ try {
+ const { getFFmpegFallback } = await import("@openreel/core/media");
+ const ffmpeg = getFFmpegFallback();
+ const wavBlob = await ffmpeg.extractAudioAsWav(blob, audioTrackIndex);
+ const arrayBuffer = await wavBlob.arrayBuffer();
+ return await audioContext.decodeAudioData(arrayBuffer);
+ } catch {
+ // ffmpeg extraction failed — fall back to browser decode for primary track
+ }
+
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.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;
}
+ return null;
};
const rendererRef = useRef<Renderer | null>(null);
@@ -2047,7 +2001,7 @@ export const Preview: React.FC = () => {
startTime: audioClip.startTime,
endTime: audioClip.startTime + audioClip.duration,
mediaOffset: audioClip.inPoint || 0,
- volume: 1,
+ volume: audioClip.volume ?? 1,
pan: 0,
effects: [],
speed: audioClip.speed ?? 1,
diff --git a/packages/core/src/audio/audio-engine.ts b/packages/core/src/audio/audio-engine.ts
index 364d47dd..446a01b7 100644
--- a/packages/core/src/audio/audio-engine.ts
+++ b/packages/core/src/audio/audio-engine.ts
@@ -42,11 +42,10 @@ class SegmentedAudioDecoder {
}) as unknown as MediaBunnyAudioInput;
const audioTracks = await this.input.getAudioTracks();
- let audioTrack =
- audioTracks[this.audioTrackIndex] ??
- (await this.input.getPrimaryAudioTrack()) ??
- audioTracks[0] ??
- null;
+ let audioTrack = audioTracks[this.audioTrackIndex] ?? null;
+ if (!audioTrack && this.audioTrackIndex === 0) {
+ audioTrack = (await this.input.getPrimaryAudioTrack()) ?? audioTracks[0] ?? null;
+ }
if (!audioTrack) {
this.dispose();
@@ -348,9 +347,7 @@ export class AudioEngine {
context: BaseAudioContext,
audioTrackIndex: number = 0,
): Promise<AudioBuffer | null> {
- const cacheKey = audioTrackIndex > 0
- ? `${mediaItem.id}:${audioTrackIndex}`
- : mediaItem.id;
+ const cacheKey = `${mediaItem.id}:${audioTrackIndex}`;
const cached = this.mediaBuffers.get(cacheKey);
if (cached) return cached;
@@ -360,31 +357,30 @@ export class AudioEngine {
}
try {
- if (audioTrackIndex === 0) {
- const arrayBuffer = await mediaItem.blob.arrayBuffer();
- const audioBuffer = await context.decodeAudioData(arrayBuffer);
+ const audioBuffer = await this.extractAudioFromVideo(
+ mediaItem,
+ context,
+ audioTrackIndex,
+ );
+ if (audioBuffer) {
this.mediaBuffers.set(cacheKey, audioBuffer);
return audioBuffer;
}
} catch {
- // Fall through to mediabunny extraction
+ // mediabunny extraction failed
}
- if (mediaItem.type === "video" || audioTrackIndex > 0) {
+ if (audioTrackIndex === 0) {
try {
- const audioBuffer = await this.extractAudioFromVideo(
- mediaItem,
- context,
- audioTrackIndex,
- );
- if (audioBuffer) {
- this.mediaBuffers.set(cacheKey, audioBuffer);
- return audioBuffer;
- }
+ const arrayBuffer = await mediaItem.blob.arrayBuffer();
+ const audioBuffer = await context.decodeAudioData(arrayBuffer);
+ this.mediaBuffers.set(cacheKey, audioBuffer);
+ return audioBuffer;
} catch {
- // Video audio extraction failed
+ return null;
}
}
+
return null;
}
@@ -396,95 +392,12 @@ export class AudioEngine {
if (!mediaItem.blob) return null;
try {
- const mediabunny = await import("mediabunny");
- const { Input, ALL_FORMATS, BlobSource, AudioSampleSink } = mediabunny;
-
- const input = new Input({
- source: new BlobSource(mediaItem.blob),
- formats: ALL_FORMATS,
- });
-
- const audioTracks = await input.getAudioTracks();
- let audioTrack =
- audioTracks[audioTrackIndex] ??
- (await input.getPrimaryAudioTrack()) ??
- audioTracks[0] ??
- null;
-
- const canDecode = await audioTrack.canDecode();
- if (!canDecode) {
- input[Symbol.dispose]?.();
- return null;
- }
-
- const duration = await audioTrack.computeDuration();
- if (!duration || duration <= 0) {
- input[Symbol.dispose]?.();
- return null;
- }
-
- const sampleRate = context.sampleRate;
- const channels = 2;
- const samplesPerSecond = 1000;
- const totalSamplePoints = Math.ceil(duration * samplesPerSecond);
-
- const sink = new AudioSampleSink(audioTrack);
- const timestamps = Array.from(
- { length: totalSamplePoints },
- (_, i) => i / samplesPerSecond,
- );
-
- const allSamples: Float32Array[] = [];
-
- for await (const sample of sink.samplesAtTimestamps(timestamps)) {
- if (!sample) {
- allSamples.push(new Float32Array(0));
- continue;
- }
- const bytesNeeded = sample.allocationSize({
- format: "f32",
- planeIndex: 0,
- });
- const floats = new Float32Array(bytesNeeded / 4);
- sample.copyTo(floats, { format: "f32", planeIndex: 0 });
- allSamples.push(floats);
- sample.close();
- }
-
- input[Symbol.dispose]?.();
-
- const totalFrames = Math.ceil(duration * sampleRate);
- const leftChannel = new Float32Array(totalFrames);
- const rightChannel = new Float32Array(totalFrames);
-
- let frameIndex = 0;
- for (const sampleData of allSamples) {
- if (sampleData.length === 0) continue;
- const numChannels = sampleData.length >= 2 ? 2 : 1;
- const framesInSample = Math.floor(sampleData.length / numChannels);
-
- for (let i = 0; i < framesInSample && frameIndex < totalFrames; i++) {
- if (numChannels === 2) {
- leftChannel[frameIndex] = sampleData[i * 2] || 0;
- rightChannel[frameIndex] = sampleData[i * 2 + 1] || 0;
- } else {
- leftChannel[frameIndex] = sampleData[i] || 0;
- rightChannel[frameIndex] = sampleData[i] || 0;
- }
- frameIndex++;
- }
- }
-
- if (frameIndex === 0) {
- return null;
- }
-
- const audioBuffer = context.createBuffer(channels, frameIndex, sampleRate);
- audioBuffer.copyToChannel(leftChannel.subarray(0, frameIndex), 0);
- audioBuffer.copyToChannel(rightChannel.subarray(0, frameIndex), 1);
-
- return audioBuffer;
- } catch (error) {
+ const { getFFmpegFallback } = await import("../media/ffmpeg-fallback");
+ const ffmpeg = getFFmpegFallback();
+ const wavBlob = await ffmpeg.extractAudioAsWav(mediaItem.blob, audioTrackIndex);
+ const arrayBuffer = await wavBlob.arrayBuffer();
+ return await context.decodeAudioData(arrayBuffer);
+ } catch {
return null;
}
}
@@ -623,9 +536,7 @@ export class AudioEngine {
return null;
}
- const cacheKey = audioTrackIndex > 0
- ? `${mediaItem.id}:${audioTrackIndex}`
- : mediaItem.id;
+ const cacheKey = `${mediaItem.id}:${audioTrackIndex}`;
const cached = this.segmentedAudioDecoders.get(cacheKey);
if (cached) {
return cached;
diff --git a/packages/core/src/media/ffmpeg-fallback.ts b/packages/core/src/media/ffmpeg-fallback.ts
index 9007bb4e..8e8fb961 100644
--- a/packages/core/src/media/ffmpeg-fallback.ts
+++ b/packages/core/src/media/ffmpeg-fallback.ts
@@ -292,7 +292,7 @@ export class FFmpegFallback {
});
}
- async extractAudioAsWav(file: File | Blob): Promise<Blob> {
+ async extractAudioAsWav(file: File | Blob, streamIndex?: number): Promise<Blob> {
await this.load();
this.ensureLoaded();
@@ -303,18 +303,20 @@ export class FFmpegFallback {
const inputData = await this.fileToUint8Array(file);
await this.ffmpeg!.writeFile(inputFilename, inputData);
- await this.ffmpeg!.exec([
- "-i",
- inputFilename,
- "-vn", // No video
- "-acodec",
- "pcm_f32le", // 32-bit float PCM
- "-ar",
- "48000", // 48kHz sample rate
- "-ac",
- "2", // Stereo
+ const args = ["-i", inputFilename];
+ if (streamIndex !== undefined) {
+ args.push("-map", `0:a:${streamIndex}`);
+ } else {
+ args.push("-vn");
+ }
+ args.push(
+ "-acodec", "pcm_f32le",
+ "-ar", "48000",
+ "-ac", "2",
outputFilename,
- ]);
+ );
+
+ await this.ffmpeg!.exec(args);
const data = await this.ffmpeg!.readFile(outputFilename);
return new Blob([data.buffer as ArrayBuffer], { type: "audio/wav" });