使用 videojs-http-streaming 支持带内字幕
随着 videojs-http-streaming (VHS) v1.2.0 于 2018 年 7 月 16 日发布,Video.js 已内置支持 FMP4 片段中携带的 CEA/CTA-608 字幕。这意味着隐藏式字幕会自动解析并提供给 Video.js 播放器,用于 MPEG-DASH 内容和使用 FMP4 片段的 HLS 流。这是一个显示字幕的示例播放器(“CC”按钮旁的英语是包含 CEA-608 字幕的轨道)。
如果您对 CEA-608 字幕以及我们用于从 FMP4 中解析它们的方法感兴趣,或者想了解大致概况,可以观看我在 Demuxed 2018 上的演讲。
字幕解析由 mux.js 库处理,并与 VHS 交互,将解析后的字幕反馈给 Video.js。
用法
创建 CaptionParser
import { CaptionParser } from 'mux.js/lib/mp4';
const captionParser = new CaptionParser();
// initalize the CaptionParser to ensure that it is ready for data
if (!captionParser.isInitialized()) {
captionParser.init();
}
当处理包含 FMP4 片段的 HLS 和 MPEG-DASH 时,用于解析字幕所需的所有信息可能不会完全包含在媒体片段本身中,并且需要将来自 init
片段的元数据传递给 CaptionParser。因此,应将 init
片段中定义的视频 trackIds 和 timescales 传递给 CaptionParser。
import mp4probe from 'mux.js/lib/mp4/probe';
// Typed array containing video and caption data
const data = new Uint8Array();
// Timescale = 90000
const timescales = mp4probe.timescale(data);
// trackId = 1
const videoTrackIds = mp4probe.videoTrackIds(data);
// Parsed captions are returned
const parsed = captionParser.parse(
data,
videoTrackIds,
timescales
);
使用包含 CEA-608 字幕的数据调用 captionParser.parse
将会得到一个具有以下结构的对象
{
captions: [
{
// You can ignore the startPts and endPts values here
startPts: 90000,
endPts: 99000,
// startTime and endTime can be used for caption times in the TextTrack API
startTime: 1,
endTime: 1.1,
text: 'This is a test caption',
// This is the CEA-608 "channel" the caption belongs to
stream: 'CC1'
}
],
// Includes any (or none) of: CC1, CC2, CC3, CC4
// This should match the captions returned in the above caption array
captionStreams: {
CC1: true
}
};
然后,您可以取一个字幕并创建一个 VTTCue
,通过 Video.js API 将其添加到 TextTrack
。
const player = videojs('video');
const track = player.addRemoteTextTrack({
kind: 'captions',
label: parsed.captions[0].stream,
default: true,
language: 'en'
}, false);
track.addCue(parsed.captions[0]);
VHS 默认包含在 Video.js v7.x 中。