Skip to main content

useAudioData()

Part of the @remotion/media-utils package of helper functions.

This convenience function wraps the getAudioData() function into a hook and does 3 things:

  • Keeps the audio data in a state
  • Wraps the function in a delayRender() / continueRender() pattern.
  • Handles the case where the component gets unmounted while the fetching is in progress and a React error is thrown.

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.

More info

Arguments

src

A string pointing to an audio asset.

Return value

AudioData | null - An object containing audio data (see documentation of getAudioData()) or null if the data has not been loaded.

Example

tsx
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>;
};
tsx
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>;
};

Errors

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.

See also