packages/docs/docs/use-audio-data.mdx
Part of the @remotion/media-utils package of helper functions.
This convenience function wraps the getAudioData() function into a hook and does 3 things:
delayRender() / continueRender() pattern.Using this function, you can elegantly render a component based on audio properties, for example together with the visualizeAudio() function.
:::info Remote audio files need to support CORS.
<details> <summary>More info</summary> <ul> <li> Remotion's origin is usually <code>http://localhost:3000</code>, but it may be different if rendering on Lambda or the port is busy. </li> <li> You can use{' '} <a href="/docs/get-audio-duration-in-seconds"> <code>getAudioDurationInSeconds()</code> </a>{' '} without the audio needing CORS. </li> <li> You can <a href="/docs/chromium-flags#--disable-web-security">disable CORS</a> during renders. </li> </ul> </details> :::srcA string pointing to an audio asset.
options?<AvailableFrom v="4.0.458"/>sampleRate?<AvailableFrom v="4.0.458"/>The sampleRate that should be passed into the AudioContext constructor. If not provided, the default value is 48000.
requestInit?<AvailableFrom v="4.0.458"/>RequestInit
Options that are passed to the fetch() call when loading the audio source.
This can be used to load authenticated remote audio files:
// ---cut---
import {useAudioData} from '@remotion/media-utils';
export const MyComponent: React.FC = () => {
const audioData = useAudioData('https://example.com/authenticated-audio.mp3', {
requestInit: {
credentials: 'include',
},
});
if (!audioData) {
return null;
}
return <div>This file has a {audioData.sampleRate} sampleRate.</div>;
};
Only the requestInit from the first render is used; updates on later renders are ignored. That keeps hook dependencies stable when you pass an inline object every render (for example {credentials: 'include'}).
AudioData | null - An object containing audio data (see documentation of getAudioData()) or null if the data has not been loaded.
// ---cut---
import {useAudioData} from '@remotion/media-utils';
import {staticFile} from 'remotion';
export const MyComponent: React.FC = () => {
const audioData = useAudioData(staticFile('music.mp3'));
if (!audioData) {
return null;
}
return <div>This file has a {audioData.sampleRate} sampleRate.</div>;
};
If you pass in a file that has no audio track, this hook will throw an error (from v4.0.75) or lead to an unhandled rejection (until v4.0.74).
To determine if a file has an audio track, you may use the getVideoMetadata() function on the server to reject a file if it has no audio track. To do so, check if the audioCodec field is null.
If you want to catch the error in the component, you need to make your own inline hook by taking the source code from the bottom of this page.
UseAudioDataOptions<AvailableFrom v="4.0.458"/>import type {
UseAudioDataOptions,
// ^?
} from '@remotion/media-utils';