Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Video - File Loading Complete Event?

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.

like image 286
Matrym Avatar asked Feb 28 '11 04:02

Matrym


1 Answers

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);
like image 139
bcoughlan Avatar answered Oct 21 '22 20:10

bcoughlan