Skip to main content

convertMedia()v4.0.229

属于 @remotion/webcodecs 软件包的一部分.

🌐 Part of the @remotion/webcodecs package.

💼 重要许可免责声明
This package is licensed under the Remotion License.
We consider a team of 4 or more people a "company".

For "companies": A Remotion Company license needs to be obtained to use this package.
In a future version of @remotion/webcodecs, this package will also require the purchase of a newly created "WebCodecs Conversion Seat". Get in touch with us if you are planning to use this package.

For individuals and teams up to 3: You can use this package for free.

This is a short, non-binding explanation of our license. See the License itself for more details.
🚧 不稳定的 API
This package is experimental.
We might change the API at any time, until we remove this notice.

使用 WebCodecs@remotion/media-parser 重新编码视频。

🌐 Re-encodes a video using WebCodecs and @remotion/media-parser.

Converting a video
import {convertMedia} from '@remotion/webcodecs'; const result = await convertMedia({ src: 'https://remotion.media/BigBuckBunny.mp4', container: 'webm', }); // Save the converted video as a Blob const blob = await result.save();

返回值

🌐 Return value

convertMedia() 返回一个 Promise,该 Promise 解析为一个具有以下属性的 ConvertMediaResult 对象:

save()

返回 Promise<Blob> 的函数

🌐 Function that returns Promise<Blob>

调用此函数以获取转换后的视频作为 Blob。然后你可以使用此 blob 来:

🌐 Call this function to get the converted video as a Blob. You can then use this blob to:

  • 创建下载链接
  • 上传到服务器
  • 在视频元素中显示
  • 存储在IndexedDB中
Saving and downloading a converted video
import {convertMedia} from '@remotion/webcodecs'; const result = await convertMedia({ src: 'https://remotion.media/BigBuckBunny.mp4', container: 'webm', }); const blob = await result.save(); // Create a download link const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'converted-video.webm'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);

remove()

返回 Promise<void> 的函数

🌐 Function that returns Promise<void>

调用此函数以清理在转换过程中创建的任何临时资源。

🌐 Call this function to clean up any temporary resources created during the conversion process.

finalState

类型为 ConvertMediaProgress 的对象

🌐 object of type ConvertMediaProgress

包含转换过程的最终状态,包括有关转换的统计信息。

🌐 Contains the final state of the conversion process, including statistics about the conversion.

应用编程接口

🌐 API

src

一个 URL 或 File/Blob,或本地文件路径。

🌐 A URL or File/Blob, or a local file path.

如果传递本地文件,曲目只能被复制,并且 reader 字段必须设置为 nodeReader

🌐 If passing a local file, tracks can only be copied, and the reader field must be set to nodeReader.

container

字符串 ConvertMediaContainer

🌐 string ConvertMediaContainer

要转换到的容器格式。目前支持 "mp4""webm""wav"

🌐 The container format to convert to. Currently, "mp4", "webm" and "wav" is supported.

expectedDurationInSeconds?

number

传递输出视频的预期时长(以秒为单位),以便可以较好地估算 MP4 元数据部分的大小。如果未传递该值,将为 MP4 元数据部分分配 2MB。

🌐 Pass the expected duration of the output video in seconds, so that the size of the MP4 metadata section can be estimated well. If the value is not passed, 2MB will be allocated for the MP4 metadata section.

如果大小超出(对于大约 1 小时或更长的视频),最终渲染可能会失败。

🌐 If the size is exceeded (for videos which are around 1 hour or longer), the render may fail in the end.

expectedFrameRate?

number

传递输出视频的预期帧率,以便可以很好地估算 MP4 元数据部分的大小。如果未传递该值,将使用 60 作为保守回退值。

🌐 Pass the expected frame rate of the output video, so that the size of the MP4 metadata section can be estimated well. If the value is not passed, 60 will be used as a conservative fallback.

videoCodec?

字符串 ConvertMediaVideoCodec

🌐 string ConvertMediaVideoCodec

要转换的视频编解码器。目前支持 "h264""h265""vp8""vp9"。 默认值由 getDefaultVideoCodec() 定义。 如果提供了 onVideoTrack 处理程序,它将覆盖此设置。

🌐 The video codec to convert to. Currently, "h264", "h265", "vp8" and "vp9" are supported.
The default is defined by getDefaultVideoCodec().
If a onVideoTrack handler is provided, it will override this setting.

audioCodec?

字符串 ConvertMediaAudioCodec

🌐 string ConvertMediaAudioCodec

要转换到的音频编解码器。目前,仅支持 "opus"
默认值由 getDefaultAudioCodec() 定义。
如果提供了 onAudioTrack 处理程序,它将覆盖此设置。

🌐 The audio codec to convert to. Currently, only "opus" is supported.
The default is defined by getDefaultAudioCodec().
If an onAudioTrack handler is provided, it will override this setting.

controller?

一个 controller 对象,允许你暂停、恢复和中止转换过程。

🌐 A controller object that allows you to pause, resume and abort the conversion process.

reader?

一个阅读器界面。

🌐 A reader interface.

默认值:webReader,允许 URL 和 File 对象。

🌐 Default value: webReader, which allows URLs and File objects.

rotate?

number

旋转视频的角度。更多信息请参见旋转视频

🌐 The number of degrees to rotate the video. See Rotate a video for more information.

resize?

对象 ResizeOperation

🌐 object ResizeOperation

调整视频大小。更多信息请参见 调整视频大小

🌐 Resize the video. See Resize a video for more information.

logLevel?

字符串 LogLevel

🌐 string LogLevel

"error""warn""info""debug""trace" 之一。
默认值:"info",仅记录重要信息。

🌐 One of "error", "warn", "info", "debug", "trace".
Default value: "info", which logs only important information.

onProgress?

函数 ConvertMediaOnProgress

🌐 Function ConvertMediaOnProgress

允许接收进度更新。可用的字段如下:

🌐 Allows receiving progress updates. The following fields are available:

import type {ConvertMediaOnProgress, ConvertMediaProgress} from '@remotion/webcodecs';

export const onProgress: ConvertMediaOnProgress = ({decodedVideoFrames, decodedAudioFrames, encodedVideoFrames, encodedAudioFrames, bytesWritten, millisecondsWritten, expectedOutputDurationInMs, overallProgress}: ConvertMediaProgress) => {
  console.log(decodedVideoFrames);
(parameter) decodedVideoFrames: number
console.log(decodedAudioFrames);
(parameter) decodedAudioFrames: number
console.log(encodedVideoFrames);
(parameter) encodedVideoFrames: number
console.log(encodedAudioFrames);
(parameter) encodedAudioFrames: number
console.log(bytesWritten);
(parameter) bytesWritten: number
console.log(millisecondsWritten);
(parameter) millisecondsWritten: number
console.log(expectedOutputDurationInMs);
(parameter) expectedOutputDurationInMs: number | null
console.log(overallProgress);
(parameter) overallProgress: number | null
};

onVideoFrame?

函数 ConvertMediaOnVideoFrame

🌐 Function ConvertMediaOnVideoFrame

允许你钩子到视频帧。这些帧是VideoFrame对象。

🌐 Allows you to hook into the video frames. The frames are VideoFrame objects.

import type {ConvertMediaOnVideoFrame} from '@remotion/webcodecs';

export const onVideoFrame: ConvertMediaOnVideoFrame = ({frame}) => {
  console.log(frame);
(parameter) frame: VideoFrame
// Do something with the frame, for example: // - Draw to a canvas // - Modify the frame // Then return the frame to be used for encoding. return frame; };

回调函数可以是异步的。

🌐 The callback function may be async.

当函数返回时,返回的帧将用于视频编码。
你可以返回相同的帧,也可以用新的 VideoFrame 对象替换它。

🌐 When the function returns, the returned frame is used for video encoding.
You may return the same frame or replace it with a new VideoFrame object.

在函数返回后,convertMedia() 将对输入和输出帧调用 .close()
这将销毁帧并释放内存。
如果你需要对帧进行引用,使其生命周期长于此函数的执行时间,必须对其调用 .clone()

🌐 After the function returns, convertMedia() will call .close() on the input and output frames.
This will destroy the frame and free up memory. If you need a reference to the frame that lasts longer than the lifetime of this function, you must call .clone() on it.

如果你返回的帧与接收到的帧不同,则它必须具有与输入帧相同的 codedWidthcodedHeightdisplayWidthdisplayHeighttimestampduration 值。

🌐 If you return a different frame than the one you received, it must have the same values for codedWidth, codedHeight, displayWidth and displayHeight, timestamp and duration as the input frame.

onAudioData?

函数 ConvertMediaOnAudioData

🌐 Function ConvertMediaOnAudioData

允许你挂接到音频数据。这些项是本地 AudioData 对象。

🌐 Allows you to hook into the audio data. The items are native AudioData objects.

import type {ConvertMediaOnAudioData} from '@remotion/webcodecs';

export const onAudioData: ConvertMediaOnAudioData = ({audioData}) => {
  console.log(audioData);
(parameter) audioData: AudioData
// Do something with the audiodata, for example: // - Change the pitch // - Lower the volume // Then return the frame to be used for encoding. return audioData; };

回调函数可以是异步的。

🌐 The callback function may be async.

当函数返回时,返回的音频数据用于音频编码。
你可以返回相同的音频数据,也可以用新的 AudioData 对象替换它。

🌐 When the function returns, the returned audio data is used for audio encoding.
You may return the same audio data or replace it with a new AudioData object.

函数返回后,convertMedia() 将在输入和输出音频数据上调用 .close()。 这将销毁音频数据并释放内存。 如果你需要一个比此函数生命周期更长的音频数据引用,你必须在它上面调用 .clone()

🌐 After the function returns, convertMedia() will call .close() on the input and output audio data.
This will destroy the audio data and free up memory. If you need a reference to the audio data that lasts longer than the lifetime of this function, you must call .clone() on it.

如果你返回的音频数据与接收到的不同,它应该具有与输入音频数据相同的 durationnumberOfChannelssampleRatetimestampnumberOfChannelsformatnumberOfChannels

🌐 If you return a different audio data than the one you received, it should have the same duration, numberOfChannels, sampleRate, timestamp, numberOfChannels, format and numberOfChannels as the input audio data.

writer?

对象 WriterInterface

🌐 object WriterInterface

一个写入器接口。以下接口可用:

🌐 A writer interface. The following interfaces are available:

Buffer writer
import {bufferWriter} from '@remotion/webcodecs/buffer';
(alias) const bufferWriter: WriterInterface import bufferWriter

写入可调整大小的数组缓冲区。

🌐 Write to a resizable Array Buffer.

Web File System writer
import {canUseWebFsWriter, webFsWriter} from '@remotion/webcodecs/web-fs';
(alias) const webFsWriter: WriterInterface import webFsWriter
await canUseWebFsWriter(); // boolean

使用 Web 文件系统 API 写入文件。

🌐 Use the Web File System API to write to a file.

默认情况下,作者是 webFsWriter

🌐 By default the writer is webFsWriter.

onAudioTrack?

函数 ConvertMediaOnAudioTrackHandler

🌐 Function ConvertMediaOnAudioTrackHandler

控制文件中每个音轨的处理方式:重新编码、复制或丢弃。
有关如何使用此回调的指南,请参阅 Track Transformation

🌐 Take control of what to do for each audio track in the file: Re-encoding, copying, or dropping.
See Track Transformation for a guide on how to use this callback.

onVideoTrack?

函数 ConvertMediaOnVideoTrackHandler

🌐 Function ConvertMediaOnVideoTrackHandler

控制对文件中的每个视频轨道执行什么操作:重新编码、复制或丢弃。
请参阅 轨道转换 获取关于如何使用此回调的指南。

🌐 Take control of what to do for each video track in the file: Re-encoding, copying, or dropping.
See Track Transformation for a guide on how to use this callback.

selectM3uStream?

函数 SelectM3uStreamFn

🌐 Function SelectM3uStreamFn

当检测到具有多个流的 .m3u8 文件时调用的回调函数。
示例见 流选择

🌐 A callback that is called when a .m3u8 file is detected which has multiple streams.
See Stream selection for an example.

progressIntervalInMs?

number

onProgress 回调被调用的时间间隔(以毫秒为单位)。
默认值为 100。设置为 0 可进行无限制更新。
请注意,更新会非常频繁,而频繁更新 DOM 可能会减慢转换过程。

🌐 The interval in milliseconds at which the onProgress callback is called.
Default 100. Set to 0 for unthrottled updates.
Note that updates are fired very often and updating the DOM often may slow down the conversion process.

seekingHints?

包含有关媒体文件结构的提示的对象。

🌐 An object that contains hints about the structure of the media file.

有关更多信息,请参阅 寻求提示

🌐 See Seeking Hints for more information.

fields? 和回调

🌐 fields? and Callbacks

在转换视频文件的过程中,你可以获取有关该视频文件的信息。 该功能继承自parseMedia(),但仅提供回调风格的 API。

🌐 You can obtain information about the video file while you are converting it.
This feature is inherited from parseMedia(), but only the callback-style API is available.

Converting a video
import {convertMedia} from '@remotion/webcodecs'; const result = await convertMedia({ src: 'https://remotion.media/BigBuckBunny.mp4', container: 'webm', videoCodec: 'vp8', audioCodec: 'opus', fields: { size: true, }, onSize: (size) => { console.log(size);
(parameter) size: number | null
}, }); const blob = await result.save();

许可证

🌐 License

参见关于 @remotion/webcodecs 的注释

另请参阅

🌐 See also