HTML5 Video - File Loading Complete Event?

Matrym picture Matrym · Feb 28, 2011 · Viewed 19.3k times · Source

I need to detect when a video file has completed loading. I'm thinking I should use progress->buffer, but in the back of my mind, I remember reading that this was unreliable. Is there a better way, or is this safe?

Note, I will be keeping a localStorage cache of videos that have been completely downloaded by each user, so I'll know in advance if a video has already loaded, and could probably bypass progress->buffer if that's a sticking point.

Thanks in advance.

Answer

bcoughlan picture bcoughlan · Mar 18, 2011

You can bind the "buffered" event, but (in Chrome at least) this works fine except that it doesn't call the last "buffered" event (i.e. it will detect 90%...94%...98%... but won't call on 100%).

Note: recent versions of jQuery should use .prop() instead of .attr()

To get around this I've used setInterval() to check the buffer every 500ms (where $html5Video is your <video> element:

var videoDuration = $html5Video.attr('duration');

var updateProgressBar = function(){
    if ($html5Video.attr('readyState')) {
        var buffered = $html5Video.attr("buffered").end(0);
        var percent = 100 * buffered / videoDuration;

        //Your code here

        //If finished buffering buffering quit calling it
        if (buffered >= videoDuration) {
                clearInterval(this.watchBuffer);
        }
    }
};
var watchBuffer = setInterval(updateProgressBar, 500);