Video.js 博客

Lahiru Dayananda2019-01-16

使用 videojs-http-streaming 支持带内字幕

随着 2018 年 7 月 16 日 videojs-http-streaming (VHS) v1.2.0 版本的发布,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 片段中的视频 trackId 和 timescale 应传递给 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 中。