Javascript:加载视频时出错,但只是在Chrome上



我有一个HTML页面,它加载视频并显示下载进度条。

视频元素是这样创建的:

function createVideo() {  
var video = document.createElement("VIDEO");
video.setAttribute('controls', '');
video.setAttribute('preload', 'auto');
video.setAttribute('width', width);
video.setAttribute('id', 'video');
var source = document.createElement("SOURCE");
source.setAttribute('src', "https://www.example.com/video.mp4");
source.setAttribute('type', 'video/mp4');

video.addEventListener('progress', function() {
var endBuf = this.buffered.end(0); //1
var soFar = parseInt(((endBuf / this.duration) * 100));
var progressBar = document.getElementById("progressBar");
if (soFar < 100) {
progressBar.setAttribute('value', soFar);
} else {
progressBar.style = "display:none;";
}
});

我在浏览器上的行为是这样的:

  1. Safari会显示视频页面,但视频不会自动播放。控制台上没有显示错误
  2. Firefox自动播放视频,并在控制台上显示没有错误
  3. Chrome自动播放视频并在控制台上显示此错误:

2codes.js:368未捕获的DOMException:未能对"TimeRanges"执行"end":提供的索引(0(大于或等于最大绑定(0(。在HTMLVideoElement上。(https://example.com/code.js:368:32)(匿名(@functions.js:368

第368行是上面代码上用//1标记的行。

我该如何解决?

Chrome可能在视频完全加载之前触发了您的"进度"侦听器,这意味着this.buffered还没有TimeRanges。如果缓冲区没有指定TimeRanges,您可以考虑将"进度"侦听器的主体包装在一条语句中进行处理:

video.addEventListener('progress', function() {
if(this.buffered.length > 0) {
var endBuf = this.buffered.end(0);
var soFar = parseInt(((endBuf / this.duration) * 100));
var progressBar = document.getElementById("progressBar");
if (soFar < 100) {
progressBar.setAttribute('value', soFar);
} else {
progressBar.style = "display:none;";
}
} else {
progressBar.style = "display:none;";
}
});

最新更新