Getting audio duration with Mediabunny
Mediabunny can extract the duration of an audio file. It works in browser, Node.js, and Bun environments.
Mediabunny can extract the duration of an audio file. It works in browser, Node.js, and Bun environments.
--- name: get-audio-duration description: Getting the duration of an audio file in seconds with Mediabunny metadata: tags: duration, audio, length, time, seconds, mp3, wav ---
Mediabunny can extract the duration of an audio file. It works in browser, Node.js, and Bun environments.
import { Input, ALL_FORMATS, UrlSource } from "mediabunny";
export const getAudioDuration = async (src: string) => {
const input = new Input({
formats: ALL_FORMATS,
source: new UrlSource(src, {
getRetryDelay: () => null,
}),
});
const durationInSeconds = await input.computeDuration();
return durationInSeconds;
};const duration = await getAudioDuration("https://remotion.media/audio.mp3");
console.log(duration); // e.g. 180.5 (seconds)For local files, use `FileSource` instead of `UrlSource`:
import { Input, ALL_FORMATS, FileSource } from "mediabunny";
const input = new Input({
formats: ALL_FORMATS,
source: new FileSource(file), // File object from input or drag-drop
});
const durationInSeconds = await input.computeDuration();import { staticFile } from "remotion";
const duration = await getAudioDuration(staticFile("audio.mp3"));