Skip to content

πŸŽ₯ Make videos programmatically with React

Update convert-audiodata.ts

Jonny Burger787169b410da
diff --git a/packages/media/src/convert-audiodata/convert-audiodata.ts b/packages/media/src/convert-audiodata/convert-audiodata.ts
index d2947dedf1..6ad7034f38 100644
--- a/packages/media/src/convert-audiodata/convert-audiodata.ts
+++ b/packages/media/src/convert-audiodata/convert-audiodata.ts
@@ -81,30 +81,38 @@ export const convertAudioData = ({
);
}
- // Always normalize through f32 to ensure consistent conversion across
- // browsers. Firefox decodes audio as f32 while Chrome decodes as s16-planar.
- // Relying on the browser's AudioData.copyTo() for the f32β†’s16 conversion
- // produces different results per browser. By always going through f32 and
- // converting to s16 ourselves, we guarantee identical output.
- const srcChannels = new Int16Array(srcNumberOfChannels * frameCount);
- const f32Temp = new Float32Array(frameCount);
-
+ // Normalize to f32-planar first, then convert to s16. This ensures
+ // consistent output across browsers β€” Firefox decodes as f32 while
+ // Chrome decodes as s16-planar, and their native copyTo(s16) conversions
+ // can differ. By going through a f32-planar AudioData, the final s16
+ // conversion always starts from the same representation.
+ const bytesPerPlane = frameCount * 4;
+ const f32Buffer = new ArrayBuffer(srcNumberOfChannels * bytesPerPlane);
for (let ch = 0; ch < srcNumberOfChannels; ch++) {
- audioData.copyTo(f32Temp, {
- planeIndex: ch,
- frameOffset,
- frameCount,
- format: 'f32-planar',
- });
- for (let i = 0; i < frameCount; i++) {
- const clamped = Math.max(-1, Math.min(1, f32Temp[i]));
- srcChannels[i * srcNumberOfChannels + ch] = Math.max(
- -32768,
- Math.min(32767, Math.round(clamped * 32768)),
- );
- }
+ audioData.copyTo(
+ new Float32Array(f32Buffer, ch * bytesPerPlane, frameCount),
+ {planeIndex: ch, frameOffset, frameCount, format: 'f32-planar'},
+ );
}
+ const f32AudioData = new AudioData({
+ format: 'f32-planar',
+ sampleRate: currentSampleRate,
+ numberOfFrames: frameCount,
+ numberOfChannels: srcNumberOfChannels,
+ timestamp: audioData.timestamp,
+ data: f32Buffer,
+ });
+
+ const srcChannels = new Int16Array(srcNumberOfChannels * frameCount);
+ f32AudioData.copyTo(srcChannels, {
+ planeIndex: 0,
+ format: 's16',
+ frameOffset: 0,
+ frameCount,
+ });
+ f32AudioData.close();
+
const data = new Int16Array(newNumberOfFrames * TARGET_NUMBER_OF_CHANNELS);
const chunkSize = frameCount / newNumberOfFrames;