How to detect whether HTML5 video has paused for buffering?

后端 未结 5 1768
长情又很酷
长情又很酷 2021-01-30 06:45

I\'m trying to test whether a video is choppy. I have noticed that the pause event is not triggered when the video pauses for buffering. What is the best way to det

5条回答
  •  一生所求
    2021-01-30 07:29

    You need to check if the buffer is less than the current video time. If so, then the video is buffering. However, you should check this with a small tolerance to make sure you detect it before it is acuatally necessary to buffer.

    Example:

    var video = document.getElementById("myVideo");
    var prevBuffer = {
        "buffer": null,
        "time": null
    };
    var isBuffering = function(){
    
        if(video && video.buffered && video.buffered.end && video.buffered.length > 0){
            var buffer = video.buffered.end(0);
            var time   = video.currentTime;
    
            // Check if the video hangs because of issues with e.g. performance
            if(prevBuffer.buffer === buffer && prevBuffer.time === time && !video.paused){
                return true;
            }
            prevBuffer = {
                "buffer": buffer,
                "time": time
            };
            // Check if video buffer is less
            // than current time (tolerance 3 sec)
            if((buffer - 3) < time){
                return true;
            }
        }
        return false;
    
    };
    video.addEventListener("play", function(e){
        // Make sure this handler is only called once
        e.target.removeEventListener(e.type, arguments.callee);
        // Give browsers 3secs time to buffer
        setTimeout(function(){
            // As "progress", "stalled" or "waiting" aren't fired
            // reliable, we need to use an interval
            var interval = setInterval(function(){
                if(isBuffering()){
                    clearInterval(interval);
                    console.log("Buffering");
                }
            }, 500);
        }, 3000);
    });
    

提交回复
热议问题