使用 videojs-http-streaming 支持带内字幕
随着 videojs-http-streaming (VHS) v1.2.0 于 2018 年 7 月 16 日发布,Video.js 内置支持 FMP4 片段中携带的 CEA/CTA-608 字幕。这意味着对于使用 FMP4 片段的 MPEG-DASH 内容和 HLS 流,隐藏式字幕会被自动解析并提供给 Video.js 播放器。这是一个 示例播放器,它显示了字幕(带有“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
片段中定义的视频轨道 ID (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 中。