我有一个 HTML5 音频播放器,我正在尝试监视它的缓冲进度,直到它达到 100%,以便我可以运行它。
music = document.querySelector("#music");
progress = document.querySelector("#progress");
music.addEventListener("progress", function(){
var z = (music.buffered.end(0) / music.duration)*100;
progress.value = z;
}, false);
(其中 #progress
是 HTML <progress>
元素。)
当我尝试上述代码时,出现此错误。
Uncaught IndexSizeError: Failed to execute 'end' on 'TimeRanges': The index provided (0) is greater than or equal to the maximum bound (0).
This error has been discussed here ,但我使用的代码与答案中使用的代码类似,但我仍然收到错误。
这是奇怪的部分:我监控了 music.buffered.length
,只达到了1
当音频完全加载时,由于某种原因我无法监视音频元素的缓冲长度。
Here's a rather robust JS Bin to show the problem.
还有其他人遇到过这个问题吗?我在这里做错了什么吗?
最佳答案
您可以在loadeddata
监听器中获取缓冲值:
audio.addEventListener ('loadeddata', function () {
if (typeof (this.buffered) !== 'undefined' && this.buffered.length > 0) {
audio.addEventListener ('progress', function () {
var z = (this.buffered.end (0) / this.duration) * 100;
progress.innerText = z;
});
}
});
请记住,它继承的是this
,而不是music
!
关于javascript - 音频缓冲在完全加载之前产生 0 TimeRanges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31376323/