我有一个 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;";
}
});
我在浏览器上的行为是这样的:
- Safari 显示视频页面,但视频不会自动播放。控制台上没有显示错误。
- Firefox 会自动播放视频,并且在控制台上不会显示任何错误。
- Chrome 会自动播放视频并在控制台上显示此错误:
2codes.js:368 Uncaught DOMException: Failed to execute 'end' on 'TimeRanges': The index provided (0) is greater than or equal to the maximum bound (0). at HTMLVideoElement. (https://example.com/code.js:368:32) (anonymous) @ functions.js:368
第 368 行是上面代码中标有//1 的行。
如何解决这个问题?
最佳答案
Chrome 可能会在视频完全加载之前触发您的“进度”监听器,这意味着 this.buffered
还没有 TimeRanges
。您可以考虑将“进度”监听器的主体包装在语句中,以处理 buffered 未指定 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;";
}
});
关于Javascript:加载视频时出错,但仅在 Chrome 上发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61351273/