Skip to main content

在 JavaScript 中获取视频的元数据

如果你想在 JavaScript 中获取视频或音频的元数据,例如:

🌐 If you would like to obtain metadata from a video or audio in JavaScript, such as:

  • 持续时间
  • 宽度和高度(尺寸)
  • 帧率(FPS)

那么 Mediabunny 就是进行此操作的理想库。

🌐 then Mediabunny is the ideal library for doing so.

从 URL 获取元数据

🌐 Getting metadata from a URL

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: videoTrack.displayWidth, height: videoTrack.displayHeight, } : null; const packetStats = await videoTrack?.computePacketStats(50); const fps = packetStats?.averagePacketRate ?? null; return { durationInSeconds, dimensions, fps, }; };
说明

我们加载一个 URL(例如 https://remotion.media/video.mp4)并使用 Mediabunny 解析它。

我们不在意格式,因此我们使用 ALL_FORMATS 加载所有解析器。

通过将 getRetryDelay 设置为 () => null,我们可以防止 Mediabunny 在请求失败时无限重试。

我们计算时长、尺寸和帧率。如果媒体文件是音频文件,我们返回 null 作为尺寸和帧率。

为了避免读取整个文件,我们最多读取 50 个数据包来计算帧率。

Usage example
import {getMediaMetadata} from './get-media-metadata'; const metadata = await getMediaMetadata('https://remotion.media/video.mp4'); console.log(metadata);
const metadata: { durationInSeconds: number; dimensions: { width: number; height: number; } | null; fps: number | null; }

为什么我们推荐Mediabunny

🌐 Why we recommend Mediabunny

Mediabunny 是一个无依赖且快速的库。

🌐 Mediabunny is a dependency-free and fast library.

它可以在浏览器中运行,但也可以在 Node.js 和 Bun 中运行。

🌐 It works in the browser, but also works in Node.js and Bun.

它支持比浏览器更多的容器格式。

🌐 It supports more container formats than the browser.

它不需要挂载 <video> 标签,这样会导致其他工作被执行(DOM 操作和视频解码)。

🌐 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.

什么时候不使用Mediabunny

🌐 When not to use Mediabunny

这些资源是使用 fetch() 加载的,所以它们必须可以被当前网站访问,并且不能被 CORS 阻止。

🌐 The assets are loaded using fetch(), so they must be accessible for the current website and not be blocked by CORS.

在这种情况下,你最好使用 @remotion/media-utils 包中的 getVideoMetadata() 函数,它在内部使用 <video> 标签。

🌐 In that case, you are better off using the getVideoMetadata() function from the @remotion/media-utils package, which uses the <video> tag internally.