Skip to main content

audioBufferToDataUrl()

Part of the @remotion/media-utils package of helper functions. Available from v2.5.7.

This API takes an AudioBuffer instance and converts it to a Base 64 Data URL so it can be passed to an <Html5Audio /> tag.

API Usage

tsx
import {audioBufferToDataUrl} from'@remotion/media-utils';
conststr=audioBufferToDataUrl(audioBuffer);

Example: Rendering a sine tone

The following composition will render a sine tone with a C4 pitch.

tsx
import {audioBufferToDataUrl} from'@remotion/media-utils';
import {useCallback, useEffect, useState} from'react';
import {Html5Audio, cancelRender, continueRender, delayRender, interpolate, useVideoConfig} from'remotion';
constC4_FREQUENCY=261.63;
constsampleRate=44100;
exportconstOfflineAudioBufferExample:React.FC= () => {
const [handle] =useState(() =>delayRender());
const [audioBuffer, setAudioBuffer] =useState<string|null>(null);
const {fps, durationInFrames} =useVideoConfig();
constlengthInSeconds= durationInFrames / fps;
constrenderAudio=useCallback(async () => {
constofflineContext=newOfflineAudioContext({
numberOfChannels: 2,
length: sampleRate * lengthInSeconds,
sampleRate,
});
constoscillatorNode= offlineContext.createOscillator();
constgainNode= offlineContext.createGain();
oscillatorNode.connect(gainNode);
gainNode.connect(offlineContext.destination);
gainNode.gain.setValueAtTime(0.5, offlineContext.currentTime);
oscillatorNode.type ='sine';
oscillatorNode.frequency.value =C4_FREQUENCY;
const {currentTime} = offlineContext;
oscillatorNode.start(currentTime);
oscillatorNode.stop(currentTime + lengthInSeconds);
constbuffer=await offlineContext.startRendering();
setAudioBuffer(audioBufferToDataUrl(buffer));
continueRender(handle);
}, [handle, lengthInSeconds]);
useEffect(() => {
renderAudio().catch((err) =>cancelRender(err));
}, [renderAudio]);
return audioBuffer ? (
<Html5Audio
src={audioBuffer}
trimAfter={100}
volume={(f) =>
interpolate(f, [0, 50, 100], [0, 1, 0], {
extrapolateLeft: 'clamp',
extrapolateRight: 'clamp',
})
}
/>
) :null;
};

See also

AltStyle によって変換されたページ (->オリジナル) /