Skip to main content

renderMedia()

自 v3.0 起可用 - @remotion/renderer 包的一部分。

以编程方式渲染视频或音频。

render.mjs
tsx
await renderMedia({
composition,
serveUrl,
codec: 'h264',
outputLocation,
inputProps,
});
render.mjs
tsx
await renderMedia({
composition,
serveUrl,
codec: 'h264',
outputLocation,
inputProps,
});

查看一个示例,展示 renderMedia()bundle()selectComposition()服务器端渲染页面上的用法。

参数

一个具有以下属性的对象:

serveUrl

string

可以是指向由 bundle() 生成的 Remotion Webpack bundle 的本地路径,也可以是存储该 bundle 的 URL。

port?

优先使用特定端口来提供 Remotion 项目。如果未指定,将使用随机端口。

outputLocation?

string - 自 v3.0.26 起可选

输出工件的保存位置。可以是绝对路径或相对路径,相对于当前工作目录解析。必须是文件路径(而不是文件夹)。

如果未指定或设置为 null,文件将以内存中的缓冲区形式返回。

composition

VideoConfig

描述使用 idwidthheightfpsdurationInFramesdefaultPropsprops 的合成的对象。
调用 selectComposition()getCompositions() 来获取可能配置的数组。

codec

"h264" | "h265" | "vp8" | "vp9" | "mp3" | "aac" | "wav" | "prores" | "h264-mkv" | "gif"

为输出媒体选择适当的编解码器。请参考编码指南以找到最适合您用例的编解码器。

inputProps?

object - 可选

传递给视频的选定合成的输入属性。
必须是 JSON 对象。
从根组件中,可以使用 getInputProps() 读取属性。
您可以使用 calculateMetadata() 转换输入属性。

确保将相同的 inputProps 传递给 selectComposition() 以使其正常工作。

frameRange?

number | [number, number] - optional

指定要渲染的单个帧(传递一个 number)或一系列帧(传递一个元组 [number, number])。通过传递 null(默认值),将渲染合成的所有帧。

concurrency?

optional

指定应同时启动多少个渲染进程的 number,指定要使用的 CPU 线程百分比的 string,或者传递 null 以让 Remotion 根据主机机器的 CPU 自行决定。默认值是可用 CPU 线程数量的一半。

logLevel?v4.0.0

One of verbose, info, warn, error.
Determines how much is being logged to the console.
verbose will also log console.log's from the browser.
Default info.

onArtifact?v4.0.176

处理由 <Artifact> 组件发出的工件

audioCodec?

"pcm-16" | "aac" | "mp3" | "opus",从 v3.3.41 开始提供

选择音频的编码方式。

  • 默认值取决于所选的 codec
  • 如果需要未压缩音频,请选择 pcm-16
  • 并非所有视频容器都支持所有音频编解码器。
  • 如果 codec 选项还指定了音频编解码器,则此选项优先。

请参阅编码指南以查看默认值和支持的组合。

audioBitrate?v3.2.32

Specify the target bitrate for the generated video. The syntax for FFmpeg's -b:a parameter should be used. FFmpeg may encode the video in a way that will not result in the exact audio bitrate specified. Example values: 512K for 512 kbps, 1M for 1 Mbps. Default: 320k

videoBitrate?v3.2.32

Specify the target bitrate for the generated video. The syntax for FFmpeg's-b:v parameter should be used. FFmpeg may encode the video in a way that will not result in the exact video bitrate specified. Example values: 512K for 512 kbps, 1M for 1 Mbps.

crf?

number | null - optional

常数速率因子,控制质量。参见:使用 CRF 设置控制质量。

bufferSize?v4.0.78

The value for the -bufsize flag of FFmpeg. Should be used in conjunction with the encoding max rate flag.

maxRate?v4.0.78

The value for the -maxrate flag of FFmpeg. Should be used in conjunction with the encoding buffer size flag.

imageFormat?

"jpeg"(默认) | "png" | "none" - 从 v3.2.27 开始可选

帧应以哪种图像格式呈现。

  • jpeg 是默认值,速度最快
  • png 如果您想要渲染透明视频
  • none 如果您正在渲染音频

browserExecutable?v3.0.11

可选

一个字符串,定义应该使用的浏览器可执行文件在磁盘上的绝对路径。默认情况下,Remotion 将尝试自动检测并下载一个,如果没有可用的。如果定义了 puppeteerInstance,它将优先于 browserExecutable

everyNthFrame?v3.1.0

可选

仅渲染每第 n 帧。例如,仅每第二帧,每第三帧等。仅适用于渲染 GIF。点击此处了解更多详情。

numberOfGifLoops?v3.1.0

可选

Allows you to set the number of loops as follows:
  • null (or omitting in the CLI) plays the GIF indefinitely.
  • 0 disables looping
  • 1 loops the GIF once (plays twice in total)
  • 2 loops the GIF twice (plays three times in total) and so on.

pixelFormat?

字符串 - 可选

要使用的自定义像素格式。 通常用于特殊用例,如透明视频。

envVariables?

Record<string, string> - 可选

一个包含要注入到项目中的环境变量的对象。

查看:环境变量

jpegQuality?

数字 - 可选

设置生成的 JPEG 图像的质量。必须是介于 0 和 100 之间的整数。默认是由浏览器决定,当前默认值为 80

仅在 imageFormat'jpeg' 时适用,否则此选项无效。

muted?v3.2.1

布尔值 - 可选

如果设置为 true,则不会渲染任何音频。

enforceAudioTrack?v3.2.1

布尔值 - 可选

如果没有其他音频轨道,则渲染一个静音音轨。

puppeteerInstance?

puppeteer.Browser - 可选

一个已打开的 Puppeteer Browser 实例。使用 openBrowser() 创建一个新实例。在多个函数调用之间重用浏览器可以加快渲染过程。您负责自行打开和关闭浏览器。如果不指定此选项,将在最后打开并关闭一个新浏览器。

scale?

可选

通过因子缩放输出尺寸。查看Scaling以了解更多关于此功能的信息。

overwrite?

布尔值 - 可选

如果设置为false,则如果文件已经存在,则不会写入输出文件。

onStart?

函数 - 可选

一旦渲染器准备好开始渲染并计算要渲染的帧数,将调用回调函数:

tsx
import {OnStartData} from '@remotion/renderer';
 
const onStart = ({
frameCount,
parallelEncoding, // available from v4.0.52
resolvedConcurrency, // available from v4.0.180
}: OnStartData) => {
console.log(`Beginning to render ${frameCount}.`);
 
if (parallelEncoding) {
console.log('Parallel encoding is enabled.');
}
 
console.log(`Using concurrency: ${resolvedConcurrency}`);
};
tsx
import {OnStartData} from '@remotion/renderer';
 
const onStart = ({
frameCount,
parallelEncoding, // available from v4.0.52
resolvedConcurrency, // available from v4.0.180
}: OnStartData) => {
console.log(`Beginning to render ${frameCount}.`);
 
if (parallelEncoding) {
console.log('Parallel encoding is enabled.');
}
 
console.log(`Using concurrency: ${resolvedConcurrency}`);
};

onProgress?

函数 - 可选

响应渲染进度。以下回调函数类似于 Remotion 在其 CLI 上显示渲染进度的方式:

简单示例 - 记录整体进度
tsx
import {RenderMediaOnProgress} from '@remotion/renderer';
 
const onProgress: RenderMediaOnProgress = ({progress}) => {
console.log(`Rendering is ${progress * 100}% complete`);
};
简单示例 - 记录整体进度
tsx
import {RenderMediaOnProgress} from '@remotion/renderer';
 
const onProgress: RenderMediaOnProgress = ({progress}) => {
console.log(`Rendering is ${progress * 100}% complete`);
};
高级示例 - 细粒度进度值
tsx
import {RenderMediaOnProgress} from '@remotion/renderer';
 
const onProgress: RenderMediaOnProgress = ({
renderedFrames,
encodedFrames,
encodedDoneIn,
renderedDoneIn,
stitchStage,
}) => {
if (stitchStage === 'encoding') {
// First pass, parallel rendering of frames and encoding into video
console.log('Encoding...');
} else if (stitchStage === 'muxing') {
// Second pass, adding audio to the video
console.log('Muxing audio...');
}
// Amount of frames rendered into images
console.log(`${renderedFrames} rendered`);
// Amount of frame encoded into a video
console.log(`${encodedFrames} encoded`);
// Time to create images of all frames
if (renderedDoneIn !== null) {
console.log(`Rendered in ${renderedDoneIn}ms`);
}
// Time to encode video from images
if (encodedDoneIn !== null) {
console.log(`Encoded in ${encodedDoneIn}ms`);
}
};
高级示例 - 细粒度进度值
tsx
import {RenderMediaOnProgress} from '@remotion/renderer';
 
const onProgress: RenderMediaOnProgress = ({
renderedFrames,
encodedFrames,
encodedDoneIn,
renderedDoneIn,
stitchStage,
}) => {
if (stitchStage === 'encoding') {
// First pass, parallel rendering of frames and encoding into video
console.log('Encoding...');
} else if (stitchStage === 'muxing') {
// Second pass, adding audio to the video
console.log('Muxing audio...');
}
// Amount of frames rendered into images
console.log(`${renderedFrames} rendered`);
// Amount of frame encoded into a video
console.log(`${encodedFrames} encoded`);
// Time to create images of all frames
if (renderedDoneIn !== null) {
console.log(`Rendered in ${renderedDoneIn}ms`);
}
// Time to encode video from images
if (encodedDoneIn !== null) {
console.log(`Encoded in ${encodedDoneIn}ms`);
}
};
note

progress 属性从 v3.2.17 版本开始可用。

onDownload?

函数 - 可选

如果您的项目中包含音频(或带有声音的视频),Remotion 需要下载它才能在输出文件中使用其音频。您可以使用此回调来响应下载的发生和进展。

tsx
import {RenderMediaOnDownload} from '@remotion/renderer';
 
const onDownload: RenderMediaOnDownload = (src) => {
console.log(`Downloading ${src}...`);
return ({percent, downloaded, totalSize}) => {
// percent and totalSize can be `null` if the downloaded resource
// does not have a `Content-Length` header
if (percent === null) {
console.log(`${downloaded} bytes downloaded`);
} else {
console.log(`${Math.round(percent * 100)}% done)`);
}
};
};
tsx
import {RenderMediaOnDownload} from '@remotion/renderer';
 
const onDownload: RenderMediaOnDownload = (src) => {
console.log(`Downloading ${src}...`);
return ({percent, downloaded, totalSize}) => {
// percent and totalSize can be `null` if the downloaded resource
// does not have a `Content-Length` header
if (percent === null) {
console.log(`${downloaded} bytes downloaded`);
} else {
console.log(`${Math.round(percent * 100)}% done)`);
}
};
};

proResProfile?

字符串 - 可选

设置 ProRes 配置文件。仅适用于使用 prores 编解码器渲染的视频。请参阅编码指南以获取可能的选项。

x264Preset?

字符串 - 可选

Sets a x264 preset profile. Only applies to videos rendered with h264 codec.
Possible values: superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo.
Default: medium

onBrowserLog?

函数 - 可选

捕获打印的控制台消息。示例:

tsx
import {BrowserLog} from '@remotion/renderer';
 
const onBrowserLog = (log: BrowserLog) => {
// `type` is the console.* method: `log`, `warn`, `error`, etc.
console.log(`[${log.type}]`);
console.log(log.text);
console.log(`at ${log.stackTrace}`);
};
tsx
import {BrowserLog} from '@remotion/renderer';
 
const onBrowserLog = (log: BrowserLog) => {
// `type` is the console.* method: `log`, `warn`, `error`, etc.
console.log(`[${log.type}]`);
console.log(log.text);
console.log(`at ${log.stackTrace}`);
};

timeoutInMilliseconds?

可选

描述渲染可能需要多长时间来解决所有 delayRender() 调用在超时之前。默认值:30000

cancelSignal?v3.0.15

可选

允许取消渲染的令牌。参见:makeCancelSignal()

chromiumOptions?v2.6.5

可选

允许您设置某些 Chromium / Google Chrome 标志。请参阅:Chromium 标志

note

需要在浏览器启动时设置 Chromium 标志。如果您通过 puppeteerInstance 传递了一个实例,则传递给 renderMedia() 的选项将不适用,而是传递给 openBrowser() 的标志。

disableWebSecurity?

boolean - 默认 false

这将主要禁用 CORS 和其他安全功能。

enableMultiProcessOnLinux?v4.0.42

boolean - 默认 true

Removes the --single-process flag that gets passed to Chromium on Linux by default. This will make the render faster because multiple processes can be used, but may cause issues with some Linux distributions or if window server libraries are missing.
Default: false until v4.0.136, then true from v4.0.137 on because newer Chrome versions don't allow rendering with the --single-process flag.
This flag will be removed in Remotion v5.0.

ignoreCertificateErrors?

boolean - 默认 false

导致无效的 SSL 证书(如自签名证书)被忽略。

headless?

If disabled, the render will open an actual Chrome window where you can see the render happen. The default is headless mode.

gl?

Changelog
  • From Remotion v2.6.7 until v3.0.7, the default for Remotion Lambda was swiftshader, but from v3.0.8 the default is swangle (Swiftshader on Angle) since Chrome 101 added support for it.
  • From Remotion v2.4.3 until v2.6.6, the default was angle, however it turns out to have a small memory leak that could crash long Remotion renders.

Select the OpenGL renderer backend for Chromium.
Accepted values:

  • "angle"
  • "egl"
  • "swiftshader"
  • "swangle"
  • "vulkan" (from Remotion v4.0.41)
  • "angle-egl" (from Remotion v4.0.51)

The default is null, letting Chrome decide, except on Lambda where the default is "swangle"

userAgent?v3.3.83

允许您设置 headless Chrome 浏览器所使用的自定义用户代理。

ffmpegOverride?v3.2.22

function - 可选

修改 Remotion 在底层使用的 FFMPEG 命令。它以 reducer 风格工作,这意味着您传递一个接受命令作为参数并返回新命令的函数。

tsx
import type {FfmpegOverrideFn} from '@remotion/renderer';
 
const ffmpegOverride: FfmpegOverrideFn = ({type, args}) => {
console.log(type); // "stitcher" | "pre-stitcher
return [...args, '-vf', 'eq=brightness=0:saturation=1'];
};
tsx
import type {FfmpegOverrideFn} from '@remotion/renderer';
 
const ffmpegOverride: FfmpegOverrideFn = ({type, args}) => {
console.log(type); // "stitcher" | "pre-stitcher
return [...args, '-vf', 'eq=brightness=0:saturation=1'];
};

您传递的函数必须接受一个对象作为唯一参数,该对象包含以下属性:

  • type:为 "stitcher""pre-stitcher"。如果有足够的内存和 CPU 可用,Remotion 可能会使用并行渲染和编码,这意味着在渲染所有帧之前会生成一个 pre-stitcher 进程。您可以通过在渲染命令中添加 --log=verbose 来判断是否启用了并行编码。
  • args:作为 FFMPEG 命令参数传递的字符串数组。

您的函数必须返回一个修改后的字符串数组。

warning

不建议使用此功能。在使用之前,我们希望让您了解一些注意事项:

  • 渲染命令可能会随着任何新的 Remotion 版本更改,即使是补丁升级也可能会破坏您对此功能的使用。
  • 根据所选的编解码器、可用的 CPU 和 RAM,Remotion 可能会或可能不会使用 "并行编码",这将导致执行多个 FFMPEG 命令。您的函数必须能够处理多次调用。
  • 当使用 Remotion Lambda 时,此功能不可用。

在您使用此技巧之前,请在Discord上联系Remotion团队,询问我们是否愿意以一种干净的方式实现您需要的功能 - 我们经常根据用户的反馈快速实现新功能。

disallowParallelEncodingv3.2.29

禁止渲染器同时进行渲染帧和编码。这使得渲染过程更节省内存,但可能会更慢。

offthreadVideoCacheSizeInBytes?v4.0.23

From v4.0, Remotion has a cache for <OffthreadVideo> frames. The default is null, corresponding to half of the system memory available when the render starts.
This option allows to override the size of the cache. The higher it is, the faster the render will be, but the more memory will be used.
The used value will be printed when running in verbose mode.
Default: null

colorSpace?v4.0.28

Color space to use for the video. Acceptable values: "default"(default since 5.0), "bt709" (since v4.0.28), "bt2020-ncl" (since v4.0.88), "bt2020-cl" (since v4.0.88), .
For best color accuracy, it is recommended to also use "png" as the image format to have accurate color transformations throughout.
Only since v4.0.83, colorspace conversion is actually performed, previously it would only tag the metadata of the video.

repro?v4.0.88

boolean - 默认为 false

Create a ZIP that you can submit to Remotion if asked for a reproduction.

binariesDirectory?v4.0.120

The directory where the platform-specific binaries and libraries that Remotion needs are located. Those include an ffmpeg and ffprobe binary, a Rust binary for various tasks, and various shared libraries. If the value is set to null, which is the default, then the path of a platform-specific package located at node_modules/@remotion/compositor-* is selected.
This option is useful in environments where Remotion is not officially supported to run like bundled serverless functions or Electron.

separateAudioTo?v4.0.123

If set, the audio will not be included in the main output but rendered as a separate file at the location you pass. It is recommended to use an absolute path. If a relative path is passed, it is relative to the Remotion Root.

forSeamlessAacConcatenation?v4.0.123

If enabled, the audio is trimmed to the nearest AAC frame, which is required for seamless concatenation of AAC files. This is a requirement if you later want to combine multiple video snippets seamlessly.

This option is used internally. There is currently no documentation yet for to concatenate the audio chunks.

onBrowserDownload?v4.0.137

Gets called when no compatible local browser is detected on the system and this API needs to download a browser. Return a callback to observe progress. See here for how to use this option.

parallelism?

在v3.2.17中更名为 concurrency。 在v4.0.0中移除。

quality?

v4.0.0中更名为 jpegQuality

dumpBrowserLogs?

可选 - 默认为 false,在v4.0中已弃用

已弃用,建议使用 logLevel

verbose?

可选,已在v4.0中弃用

已弃用,建议使用 logLevel

onSlowestFrames?

在v3.2.29中引入,从v4.0中移除。slowestFrames 已移至返回类型。

renderMedia() 解析之前调用的回调函数。
唯一的参数 slowestFrames 是一个形如 {frame:<帧编号>, time:<渲染帧所需时间 ms>} 的包含10个最慢帧的数组。您可以使用此信息来优化您的渲染时间。

ffmpegExecutable

在v4.0中移除,字符串,可选

覆盖要使用的 ffmpeg 可执行文件的绝对路径。

ffprobeExecutable? v3.0.17

在 v4.0 中移除,可选

用于覆盖 ffprobe 可执行文件的绝对路径。

返回值

从 v4.0.0 开始:

返回值是一个具有以下属性的对象:

  • buffer: 如果未指定 outputLocation 或为 null,则包含一个缓冲区,否则为 null
  • slowestFrames: 一个包含 10 个最慢帧的数组,格式为 {frame:<帧编号>, time:<渲染帧所需时间 ms>}。您可以使用此信息来优化渲染时间。

从 v3.0.26 开始:

如果未指定 outputLocation 或为 null,则返回值是一个解析为 Buffer 的 Promise。如果指定了输出位置,则返回值是一个解析为无值的 Promise。

参见