Xi *_*iao 7 html5-video vtt webvtt
我的需要
html5 video 元素加载保存在不同域中的视频和 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。
一些文章说添加crossorigin或添加crossorigin="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>Run Code Online (Sandbox Code Playgroud)
希望这有助于下一个人偶然发现这个 SO 问题。我发现 IE(10 和 11)不支持为 加载跨域 VTT 文件<track>,即使启用了 CORS。为了添加 IE 对字幕的支持,我不得不使用如下所示的脚本。
该脚本通过 AJAX 下载每个 VTT 文件,创建一个blob URL,并<track>用其各自的 blob URL替换每个src。
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();
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
小智 5
我可以确认元素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>
Run Code Online (Sandbox Code Playgroud)
最后,请记住,您必须使用 Web 服务器来提供此 HTML 片段 - 这不能在本地完成(即file//)。
如果您熟悉node- install http-server,请运行--cors并使用 ngrok。
| 归档时间: |
|
| 查看次数: |
4042 次 |
| 最近记录: |