packages/docs/docs/mediabunny/metadata.mdx
If you would like to obtain metadata from a video or audio in JavaScript, such as:
then Mediabunny is the ideal library for doing so.
import {Input, ALL_FORMATS, UrlSource} from 'mediabunny';
export const getMediaMetadata = async (src: string) => {
const input = new Input({
formats: ALL_FORMATS,
source: new UrlSource(src, {
getRetryDelay: () => null,
}),
});
const durationInSeconds = await input.computeDuration();
const videoTrack = await input.getPrimaryVideoTrack();
const dimensions = videoTrack
? {
width: await videoTrack.getDisplayWidth(),
height: await videoTrack.getDisplayHeight(),
}
: null;
const packetStats = await videoTrack?.computePacketStats(50);
const fps = packetStats?.averagePacketRate ?? null;
return {
durationInSeconds,
dimensions,
fps,
};
};
// @filename: get-media-metadata.ts
import {Input, ALL_FORMATS, UrlSource} from 'mediabunny';
export const getMediaMetadata = async (src: string) => {
const input = new Input({
formats: ALL_FORMATS,
source: new UrlSource(src, {
getRetryDelay: () => null,
}),
});
const durationInSeconds = await input.computeDuration();
const videoTrack = await input.getPrimaryVideoTrack();
const dimensions = videoTrack
? {
width: await videoTrack.getDisplayWidth(),
height: await videoTrack.getDisplayHeight(),
}
: null;
const packetStats = await videoTrack?.computePacketStats(50);
const fps = packetStats?.averagePacketRate ?? null;
return {
durationInSeconds,
dimensions,
fps,
};
};
// @filename: index.ts
// ---cut---
import {getMediaMetadata} from './get-media-metadata';
const metadata = await getMediaMetadata('https://remotion.media/video.mp4');
console.log(metadata);
// ^?
Mediabunny is a dependency-free and fast library.
It works in the browser, but also works in Node.js and Bun.
It supports more container formats than the browser.
It does not need to mount a <video> tag, which would result in other work being done (DOM manipulation and video decoding).
It can return more metadata than the browser, for example the frame rate or the codec.
The assets are loaded using fetch(), so they must be accessible for the current website and not be blocked by CORS.
In that case, you are better off using the getVideoMetadata() function from the @remotion/media-utils package, which uses the <video> tag internally.