Getting metadata from a video in JavaScript
If you would like to obtain metadata from a video or audio in JavaScript, such as:
- Duration
- Width and height (Dimensions)
- Frame rate (FPS)
then Mediabunny is the ideal library for doing so.
Getting metadata from a URL
get-media-metadata.tstsx
import {Input ,ALL_FORMATS ,UrlSource } from 'mediabunny';export constgetMediaMetadata = async (src : string) => {constinput = newInput ({formats :ALL_FORMATS ,source : newUrlSource (src , {getRetryDelay : () => null,}),});constdurationInSeconds = awaitinput .computeDuration ();constvideoTrack = awaitinput .getPrimaryVideoTrack ();constdimensions =videoTrack ? {width :videoTrack .displayWidth ,height :videoTrack .displayHeight ,}: null;constpacketStats = awaitvideoTrack ?.computePacketStats (50);constfps =packetStats ?.averagePacketRate ?? null;return {durationInSeconds ,dimensions ,fps ,};};
Explanation
We load a URL (e.g. https://remotion.media/video.mp4
) and parse it using Mediabunny.
We don't care which format, so we load all parsers using ALL_FORMATS
.
By setting getRetryDelay
to () => null
, we prevent Mediabunny from infinitely retrying if the request fails.
We compute the duration, the dimensions and the frame rate. If the media file is an audio file, we return null
for the dimensions and the frame rate.
To avoid reading the entire file, we at most read 50 packets to compute the frame rate.
Usage exampletsx
import {getMediaMetadata } from './get-media-metadata';constmetadata = awaitgetMediaMetadata ('https://remotion.media/video.mp4');console .log (metadata );
Why we recommend Mediabunny
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.
When not to use Mediabunny
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.