Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 570
user3524045 Avatar asked Sep 03 '14 18:09

user3524045


3 Answers

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+"%");
    }
}
like image 107
ksloan Avatar answered Sep 28 '22 16:09

ksloan


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+"%");
}
like image 8
Sunand Avatar answered Oct 19 '22 15:10

Sunand


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+"%");
    }
}
like image 7
user5555154 Avatar answered Oct 19 '22 17:10

user5555154