本机浏览器支持解析 <track> w/o 视频

Native browser support for parsing <track> w/o video

我正在尝试查看是否需要导入 VTT 解析器,或者我是否可以从 <track src="transcript.vtt" /> 获取 HTML。浏览器似乎已经支持解析 HTML 以在视频顶部显示,但我找不到在视频之外访问它的方法。

我怎样才能实现这样的目标:

<div>
  <random-video-player></random-video-player>
  <track src="transcript.vtt" />
  <div id="transcript" >
     // show my VTT cues
  </div>
</div>


@ViewChild('track') track: HTMLTrackElement;
track.cues.foreach(cue => {
   var cueHtmlSpecial = addSpecialAttributes(cue);
   document.getElementById("transcript").appendChild(cueHtmlSpecial)
});

我找到了一个包,或多或少应该可以按我的需要工作,但想知道是否真的需要一个包。 https://github.com/plussub/srt-vtt-parser

如果你真的只想解析 Web-VTT 那么不,你不需要额外的库。
Web-VTT API 确实已经提供了几乎所有你需要的东西。

要从 .vtt 文件中提取 VTTCues,您需要一个

const getCues = (url) => {
  // we need a <video> element, but it can stay disconnected
  // it also doesn't need to point to an actual media
  const vid = document.createElement("video");
  const track = document.createElement("track");
  track.default = true;
  vid.append(track);
  return new Promise((res, rej) => {
    track.onload = (evt) => res([...vid.textTracks[0].cues]);
    track.onerror = (evt) => rej("invalid url");
    track.src = url;
  });
};
(async () => {
  const url = getVTTURL();
  const cues = await getCues(url);
  // for the demo we log only a few properties from the VTTCue object
  console.log(cues.map(({text, startTime, endTime}) => ({text, startTime, endTime})));
})().catch(console.error);


// only for this demo, we build a full .vtt file on the fly
// and return an URL that points to this file.
function getVTTURL() {
  let vttText = `WEBVTT`;
  for( let i=0; i<35; i++ ) {
    const t1 = (i + '').padStart(2 , '0');
    const t2 = ((i+1) + '').padStart(2 , '0');
    vttText += `
      00:00:${t1}.000 --> 00:00:${t2}.000
      Test${i}`
  }
  const vttBlob = new Blob([vttText], {
    type: 'text/plain'
  });
  return URL.createObjectURL(vttBlob);
}