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

I am creating an mp3 playlist with HTML5 and jQuery. For this player, the horizontal bar grows gradually in combination with the buffered presence of the mp3 file.

here is my complete code: get buffer 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 tells me the error message:

IndexSizeError: index or size 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' in 'TimeRanges': pointer (0) is greater than or equal to maximum border (0).

+7
jquery html5-audio
source share
3 answers

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

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

The accepted answer does not solve the problem for me. You should also check that the track has loaded before you access the buffered one. So:

 track.onprogress = function(){ if (track.readyState === 4){ var w = 100*(track.buffered.end(0))/track.duration; $('#buffered').css("width",w+"%"); } } 
+3
source share
 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+"%"); } } 
+1
source share

All Articles