7

我的需要

html5 视频元素加载保存在不同域中的视频和 vtt 文件。

问题

vtt 未加载和错误Text track from origin has been blocked from loading: Not at same origin as the document, and parent of track element does not have a 'crossorigin' attribute.

我的调查

我知道需要使用 CORS,以便 vtt 可以成功加载到 html5 中。

我已经在服务器端为来自任何域的请求启用了 CORS。

有些文章说添加crossorigincrossorigin="anonymous"到`元素可以完成这项工作,但它不起作用。根本没有加载视频或出现不同的错误

我把我的代码放在下面

<body>
  <div class="container">
    <video id="myvideo" controls preload="auto" width="640" height="264" autoplay>
      <source src=http://video.dublearn.net/-KqIgE-3roMSBbiHUmLI/video.mp4 type="video/mp4"></source>
      <track kind="captions" label="English" srclang="en" src=http://video.dublearn.net/-KqIgE-3roMSBbiHUmLI/video.vtt default>
    </video>
</body>

4

2 回答 2

7

希望这有助于下一个人偶然发现这个 SO 问题。我发现 IE(10 和 11)不支持为 a 加载跨域 VTT 文件<track>,即使启用了 CORS。为了添加 IE 对字幕的支持,我不得不使用如下脚本。

此脚本通过 AJAX 下载每个 VTT 文件,创建一个blob URL,并将每个<track>src 替换为其各自的 blob URL。

window.addEventListener("load", function() {
  if (window.navigator.userAgent.indexOf("MSIE ") < 0 && window.navigator.userAgent.indexOf("Trident/") < 0) {
    // Not IE, do nothing.
    return;
  }

  var tracks = document.querySelectorAll("track")

  for (var i = 0; i < tracks.length; i++) {
    loadTrackWithAjax(tracks[i]);
  }
});

function loadTrackWithAjax(track) {
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200 && this.responseText) {
      // If VTT fetch succeeded, replace the src with a BLOB URL.
      var blob = new Blob([this.responseText], { type: 'text/vtt' });
      track.setAttribute("src", URL.createObjectURL(blob));
    }
  };
  xhttp.open("GET", track.src, true);
  xhttp.send();
}
<video controls preload width="600" height="337.5" autoplay crossorigin="anonymous">
      <source src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4" type="video/mp4"></source>
      <track kind="captions" label="English" srclang="en" src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt" default>
</video>

于 2019-11-04T17:29:46.390 回答
4

我可以确认元素crossorigin=anonymous上的属性video确实按预期加载了文本轨道。

试一下这段代码:

<video id="myvideo" controls preload="auto" width="640" height="264" autoplay crossorigin="anonymous">
      <source src=http://video.dublearn.net/-KqIgE-3roMSBbiHUmLI/video.mp4 type="video/mp4"></source>
      <track kind="captions" label="English" srclang="en" src=http://video.dublearn.net/-KqIgE-3roMSBbiHUmLI/video.vtt default>
</video>

最后,请记住,您必须使用 Web 服务器来提供此 HTML 片段 - 这不能在本地完成(即。file//​​)。

如果您熟悉node- install ,请使用 ngrokhttp-server运行和使用。--cors

于 2017-08-28T07:06:09.057 回答