[ PROMPT_NODE_27786 ]
display-captions
[ SKILL_DOCUMENTATION ]
# 在 Remotion 中显示字幕
本指南解释了如何在 Remotion 中显示字幕,假设你已经拥有 `Caption` 格式的字幕数据。
## 前置要求
首先,需要安装 @remotion/captions 包。
如果尚未安装,请使用以下命令:
bash
npx remotion add @remotion/captions # 如果项目使用 npm
bunx remotion add @remotion/captions # 如果项目使用 bun
yarn remotion add @remotion/captions # 如果项目使用 yarn
pnpm exec remotion add @remotion/captions # 如果项目使用 pnpm
## 创建页面
使用 `createTikTokStyleCaptions()` 将字幕分组为页面。`combineTokensWithinMilliseconds` 选项控制一次显示多少个单词:
tsx
import {useMemo} from 'react';
import {createTikTokStyleCaptions} from '@remotion/captions';
import type {Caption} from '@remotion/captions';
// 字幕切换频率(以毫秒为单位)
// 数值越大 = 每页显示的单词越多
// 数值越小 = 单词越少(更接近逐词显示)
const SWITCH_CAPTIONS_EVERY_MS = 1200;
const {pages} = useMemo(() => {
return createTikTokStyleCaptions({
captions,
combineTokensWithinMilliseconds: SWITCH_CAPTIONS_EVERY_MS,
});
}, [captions]);
## 使用序列 (Sequences) 进行渲染
遍历页面并在 `` 中渲染每一页。根据页面时间计算起始帧和持续时间:
tsx
import {Sequence, useVideoConfig, AbsoluteFill} from 'remotion';
import type {TikTokPage} from '@remotion/captions';
const CaptionedContent: React.FC = () => {
const {fps} = useVideoConfig();
return (
{pages.map((page, index) => {
const nextPage = pages[index + 1] ?? null;
const startFrame = (page.startMs / 1000) * fps;
const endFrame = Math.min(
nextPage ? (nextPage.startMs / 1000) * fps : Infinity,
startFrame + (SWITCH_CAPTIONS_EVERY_MS / 1000) * fps,
);
const durationInFrames = endFrame - startFrame;
if (durationInFrames <= 0) {
return null;
}
return (
);
})}
);
};
## 单词高亮
字幕页面包含 `tokens`,你可以利用它来高亮当前正在朗读的单词:
tsx
import {AbsoluteFill, useCurrentFrame, useVideoConfig} from 'remotion'