伺服器端渲染
用 Node.js API 在伺服器上渲染 Remotion 影片。
什麼是 SSR?
SSR(Server-Side Rendering)指的是用 Node.js 程式碼在伺服器上渲染影片,而不是在 Studio 或用 CLI。這適合:
- API 觸發的影片產出
- 批量渲染
- 整合到現有的後端系統
安裝
npm install @remotion/bundler @remotion/renderer三步驟流程
1. 打包(Bundle)
把你的 Remotion 專案打包成一個可被渲染的 bundle:
import { bundle } from "@remotion/bundler";
import path from "path";
const bundled = await bundle({
entryPoint: path.resolve("./src/index.ts"),
});2. 選擇 Composition
從 bundle 中選取要渲染的 Composition:
import { selectComposition } from "@remotion/renderer";
const composition = await selectComposition({
serveUrl: bundled,
id: "MyVideo",
inputProps: {
title: "動態標題",
},
});3. 渲染
import { renderMedia } from "@remotion/renderer";
await renderMedia({
composition,
serveUrl: bundled,
codec: "h264",
outputLocation: "out/video.mp4",
inputProps: {
title: "動態標題",
},
});完整範例
import { bundle } from "@remotion/bundler";
import { renderMedia, selectComposition } from "@remotion/renderer";
import path from "path";
async function renderVideo(props: Record<string, unknown>) {
console.log("正在打包...");
const bundled = await bundle({
entryPoint: path.resolve("./src/index.ts"),
});
console.log("正在選擇 Composition...");
const composition = await selectComposition({
serveUrl: bundled,
id: "MyVideo",
inputProps: props,
});
console.log("正在渲染...");
await renderMedia({
composition,
serveUrl: bundled,
codec: "h264",
outputLocation: "out/video.mp4",
inputProps: props,
onProgress: ({ progress }) => {
console.log(`進度: ${Math.round(progress * 100)}%`);
},
});
console.log("完成!");
}
renderVideo({ title: "我的影片", color: "#6366f1" });渲染靜態圖片
import { renderStill } from "@remotion/renderer";
await renderStill({
composition,
serveUrl: bundled,
output: "out/thumbnail.png",
frame: 45,
});進度回報
renderMedia 的 onProgress 回呼讓你追蹤渲染進度:
await renderMedia({
...
onProgress: ({ progress, renderedFrames, totalFrames }) => {
console.log(`${renderedFrames}/${totalFrames} 幀 (${Math.round(progress * 100)}%)`);
},
});並行渲染
控制同時渲染的幀數:
await renderMedia({
...
concurrency: 4, // 同時渲染 4 幀
});預設會自動偵測 CPU 核心數。
小結
- SSR 流程:打包 → 選擇 Composition → 渲染
- 用
@remotion/bundler打包,@remotion/renderer渲染 renderMedia輸出影片,renderStill輸出圖片onProgress追蹤渲染進度- 適合 API 觸發和批量渲染的場景