1

I'm working with HTML5, making an audio player.

I wonder to know how I can add a buffer bar so that the user can see how long the song is loaded.

I've tried using several properties that I saw in some tutorials, but none have worked, and I can not find anything about this specific topic.

This is the audio player that I'm trying to edit.

I wish someone could guide me on how to edit the code to do it, or, otherwise, recommend tutorials, documentation or any information.

Tomás Juárez
  • 1,517
  • 3
  • 21
  • 51

1 Answers1

2

There's no guarantee that all of this is going to work on all browsers...

...however, assume, for the rest of this post that:

var audio = new Audio();
audio.src = "//example.com/some-really-long-song.mp3";

"canplay" is the first useful event, in terms of being able to play the song.
It means that part of the song is ready to go, and it's at least enough to be able to hear something, if you hit the play button.

Alternatively "canplaythrough" is the browser's guess at whether you can start playing the song right now, and it will run without stopping (based on amount of data left to download, and how fast the song is currently downloading).

audio.addEventListener("canplay", function () { audio.play(); });

"durationchange" is an event which should fire when a duration changes.
For file-types which don't have metadata, or where the metadata isn't supported, the whole duration might not be available as the file starts loading.
In these cases, audio.duration might be updated by the browser downloading the first bit of the media, and then the last, and making an educated guess at the length of the file, or the duration might come from the browser having to load more and more of the file, and increasing the duration as it goes. Where we are in terms of support, I don't know.

audio.addEventListener("durationchange", function () {
    player.time.duration.update(audio.duration);
});

"progress" is an event which fires ~250ms as data is coming in (while downloading the file).
progress tells you that updates have been made to data which is available to seek through right now.

This makes it a good event to use to check your audio.buffered objects, in order to update the "loaded" portion of your progress bar.

audio.addEventListener("progress", function () {
    player.progressBar.update(audio.buffered.start(0), audio.buffered.end(0));
});

Then you can use "timeupdate" to deal with playback.
timeupdate will update a few times a second, as the song is playing (as audio.currentTime moves forward).

Norguard
  • 26,167
  • 5
  • 41
  • 49