🎥 Make videos programmatically with React
add buffer to getPartialAudioData. now it works correctly!
Igor Samokhovets689fdca25ad5
diff --git a/packages/media-utils/src/get-partial-audio-data.ts b/packages/media-utils/src/get-partial-audio-data.tsindex 9c86edbba5..6c6952aae9 100644--- a/packages/media-utils/src/get-partial-audio-data.ts+++ b/packages/media-utils/src/get-partial-audio-data.ts@@ -5,6 +5,78 @@ import {} from '@remotion/media-parser';import {createAudioDecoder} from '@remotion/webcodecs';+/**+ * Extract the portion of an audio chunk that overlaps with the requested time window+ */+const extractOverlappingAudioSamples = ({+ sample,+ fromSeconds,+ toSeconds,+ channelIndex,+ timescale,+}: {+ sample: AudioData;+ fromSeconds: number;+ toSeconds: number;+ channelIndex: number;+ timescale: number;+}): Float32Array | null => {+ const chunkStartInSeconds = sample.timestamp / timescale;+ const chunkDuration = sample.numberOfFrames / sample.sampleRate;+ const chunkEndInSeconds = chunkStartInSeconds + chunkDuration;++ // Calculate overlap with the requested window+ const overlapStartSecond = Math.max(chunkStartInSeconds, fromSeconds);+ const overlapEndSecond = Math.min(chunkEndInSeconds, toSeconds);++ // Skip if no overlap with requested window+ if (overlapStartSecond >= overlapEndSecond) {+ return null;+ }++ // For multi-channel audio, we need to handle channels properly+ const {numberOfChannels} = sample;+ const samplesPerChannel = sample.numberOfFrames;++ let data: Float32Array;++ if (numberOfChannels === 1) {+ // Mono audio+ data = new Float32Array(+ sample.allocationSize({format: 'f32', planeIndex: 0}),+ );+ sample.copyTo(data, {format: 'f32', planeIndex: 0});+ } else {+ // Multi-channel audio: extract specific channel+ const allChannelsData = new Float32Array(+ sample.allocationSize({format: 'f32', planeIndex: 0}),+ );+ sample.copyTo(allChannelsData, {format: 'f32', planeIndex: 0});++ // Extract the specific channel (interleaved audio)+ data = new Float32Array(samplesPerChannel);+ for (let i = 0; i < samplesPerChannel; i++) {+ data[i] = allChannelsData[i * numberOfChannels + channelIndex];+ }+ }++ // Calculate which samples to keep from this chunk+ const startSampleInChunk = Math.floor(+ (overlapStartSecond - chunkStartInSeconds) * sample.sampleRate,+ );+ const endSampleInChunk = Math.ceil(+ (overlapEndSecond - chunkStartInSeconds) * sample.sampleRate,+ );++ // Only keep the samples we need+ return data.slice(startSampleInChunk, endSampleInChunk);+};++// Small buffer to ensure we capture chunks that span across boundaries+// We need this because specified time window is not always aligned with the audio chunks+// so that we fetch a bit more, and then trim it down to the requested time window+const BUFFER_IN_SECONDS = 0.1;+export const getPartialAudioData = async ({src,fromSeconds,@@ -29,8 +101,13 @@ export const getPartialAudioData = async ({}// Forward abort signal immediately to the controller++ const {resolve: resolveAudioDecode, promise: audioDecodePromise} =+ Promise.withResolvers<void>();+const onAbort = () => {controller.abort();+ resolveAudioDecode();};signal.addEventListener('abort', onAbort, {once: true});@@ -45,7 +122,6 @@ export const getPartialAudioData = async ({src,controller,onAudioTrack: ({track}) => {- // Check abort signal immediately when onAudioTrack is calledif (signal.aborted) {return null;}@@ -58,42 +134,26 @@ export const getPartialAudioData = async ({return;}- // For multi-channel audio, we need to handle channels properly- const {numberOfChannels} = sample;- const samplesPerChannel = sample.numberOfFrames;-- let data: Float32Array;-- if (numberOfChannels === 1) {- // Mono audio- data = new Float32Array(- sample.allocationSize({format: 'f32', planeIndex: 0}),- );- sample.copyTo(data, {format: 'f32', planeIndex: 0});- } else {- // Multi-channel audio: extract specific channel- const allChannelsData = new Float32Array(- sample.allocationSize({format: 'f32', planeIndex: 0}),- );- sample.copyTo(allChannelsData, {format: 'f32', planeIndex: 0});-- // Extract the specific channel (interleaved audio)- data = new Float32Array(samplesPerChannel);- for (let i = 0; i < samplesPerChannel; i++) {- data[i] = allChannelsData[i * numberOfChannels + channelIndex];- }+ const trimmedData = extractOverlappingAudioSamples({+ sample,+ fromSeconds,+ toSeconds,+ channelIndex,+ timescale: track.timescale,+ });++ if (trimmedData) {+ audioSamples.push(trimmedData);}- audioSamples.push(data);sample.close();},onError(error) {+ resolveAudioDecode();throw error;},});- // The abort listener is already set up above, no need to duplicate-return async (sample) => {if (signal.aborted) {audioDecoder.close();@@ -108,16 +168,18 @@ export const getPartialAudioData = async ({// Convert timestamp using the track's timescaleconst time = sample.timestamp / track.timescale;- // Skip samples that are before our requested start time- if (time < fromSeconds) {+ // Skip samples that are before our requested start time (with buffer)+ if (time < fromSeconds - BUFFER_IN_SECONDS) {return;}- // Stop immediately when we reach our target time- if (time >= toSeconds) {+ // Stop immediately when we reach our target time (with buffer)+ if (time >= toSeconds + BUFFER_IN_SECONDS) {// wait until decoder is done- await audioDecoder.flush();- audioDecoder.close();+ audioDecoder.flush().then(() => {+ audioDecoder.close();+ resolveAudioDecode();+ });controller.abort();return;}@@ -140,7 +202,8 @@ export const getPartialAudioData = async ({signal.removeEventListener('abort', onAbort);}- // Simply concatenate all audio data since windowing handles the time ranges+ await audioDecodePromise;+ // Simply concatenate all audio data since we've already trimmed each chunkconst totalSamples = audioSamples.reduce((sum, sample) => sum + sample.length,0,