Why does audio.buffered.end(0) get an error message when I try to get buffered time

…衆ロ難τιáo~ 提交于 2019-12-12 07:33:32

问题


I'm building mp3 playlist player with HTML5 and jQuery. At this player there is a horizontal bar grow gradually in conjunction with the buffered present of mp3 file.

here is my full code: get buffered end

HTML5:

<audio id="music" controls>
  <source src="https://archive.org/download/musicTestAudio27/Very%20nice%20%2827%29.mp3" type="audio/mpeg">
</audio>
    <br/>
    <div id="buffered"></div>

CSS:

#buffered{
    border:solid #ccc 1px;
    height:10px;
    background:red;
    display:block;
    width:1%;
}

Javascript:

var track = document.getElementById("music");
setInterval(function(){
var w = 100*(track.buffered.end(0))/track.duration;
$('#buffered').css("width",w+"%");
}, 1000);

but Firefox give me an error message said:

IndexSizeError: Index or size is negative or greater than the allowed amount

var w = 100*(track.buffered.end(0))/track.duration;

and Google chrome said:

Uncaught IndexSizeError: Failed to execute 'end' on 'TimeRanges': The index provided (0) is greater than or equal to the maximum bound (0).


回答1:


I believe that error is coming when accessing buffered.end before the element is initialized. you can rewrite that code as to avoid it

track = document.getElementById("music");
track.onprogress = function(){
    var w = 100*(track.buffered.end(0))/track.duration;
    $('#buffered').css("width",w+"%");
}



回答2:


track = document.getElementById("music");
track.onprogress = function(){
    if(track.buffered.length>0){
        var w = 100*(track.buffered.end(0))/track.duration;
        $('#buffered').css("width",w+"%");
    }
}



回答3:


The accepted answer doesn't solve the problem for me. You also should check that the track has loaded before you access buffered.end like so:

track.onprogress = function(){
    if (track.readyState === 4){
        var w = 100*(track.buffered.end(0))/track.duration;
        $('#buffered').css("width",w+"%");
    }
}



回答4:


This error occurs when the audio element is not loaded yet, so there are no time ranges for the code to find so it returns an error.



来源:https://stackoverflow.com/questions/25651719/why-does-audio-buffered-end0-get-an-error-message-when-i-try-to-get-buffered-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!