渲染视频工作流
渲染是按帧捕获合成并将其编码为视频文件(例如 MP4)的过程。这通过在 Node.js 环境中使用 @helios-project/renderer 包完成。
快速路径:单条命令
npx -y @helios-project/cli@latest render composition.html -o output.mp4
- 时长、帧率(fps)和大小来自合成的
window.helios。要自己设置它们,请传递--duration、--fps、--width和--height。 - 使用
window.renderAt(t)自行绘制的页面需要--duration。 --audio track.mp3添加音轨。- 纯 HTML 文件直接从磁盘渲染。如果打包器需要构建合成,请运行
npm run dev并传递其 URLs 代替。
仅当您需要自定义管道(例如输入属性、多条音轨或进度回调)时,才使用下面的脚本。
1. 前提条件
渲染器需要合成的 URL:
- 磁盘上的文件:
file:///path/to/composition.html - 开发服务器:
npm run dev,例如http://localhost:3000/composition.html - 其他任何可访问的 URL
2. 创建渲染脚本
创建一个名为 render.js(如果使用 ts-node 则为 render.ts)的文件。
import { Renderer } from '@helios-project/renderer';
import path from 'path';
async function main() {
// 1. 配置
const compositionUrl = 'http://localhost:3000/composition.html';
const outputPath = path.resolve('output.mp4');
// 2. 初始化渲染器
const renderer = new Renderer({
width: 1920,
height: 1080,
fps: 30,
durationInSeconds: 10,
// frameCount: 300, // 可选:使用精确帧数覆盖 durationInSeconds
mode: 'canvas', // 如果动画使用 CSS/HTML 元素,请使用 'dom'
// 音频配置
audioTracks: [
{ path: 'background.mp3', volume: 0.5 },
{ path: 'voiceover.wav', offset: 2 }
],
audioCodec: 'aac',
// 输入属性(动态内容)
inputProps: {
title: "Custom Render",
color: "#00ff00"
}
});
console.log(`开始渲染 ${compositionUrl}...`);
// 3. 执行渲染
try {
await renderer.render(compositionUrl, outputPath, {
onProgress: (p) => {
const percent = Math.round(p * 100);
process.stdout.write(`\r进度: ${percent}%`);
}
});
console.log(`\n完成!已保存至 ${outputPath}`);
} catch (err) {
console.error('\n渲染失败:', err);
process.exit(1);
}
}
main();
3. 运行渲染
执行脚本。
# 如果使用 ts-node
npx ts-node render.ts
# 如果使用 node(已编译的 js)
node render.js
故障排除
“页面超时”或“连接被拒绝”
- 确保托管合成的本地服务器正在运行。
- 检查 URL 是否正确且在常规浏览器中可访问。
“输出为黑色”或“视频为空”
- 确保已暴露
window.helios(或者页面定义了window.renderAt(t))。 - 如果使用
mode: 'canvas',请确保您正在向<canvas>元素绘制。 - 如果使用
mode: 'dom',请确保元素是可见的。
“渲染挂起”
- 在浏览器控制台中检查合成是否存在错误。
- 启用跟踪进行调试:
await renderer.render(url, out, { tracePath: 'trace.zip' });
音频问题
- 确保音频文件路径相对于脚本运行位置是正确的。
- 如果使用
mode: 'dom'并依赖隐式音频(例如<audio>标签),请确保这些元素存在于 DOM 中。