Fully buffer video in Chrome

后端 未结 5 2001
我在风中等你
我在风中等你 2021-02-07 16:01

Is it possible to fully buffer HTML5 video in Chrome (and Opera)?

I host the movie in .mp4 and .webm on amazon S3. In HTML I use standard tag.

5条回答
  •  孤独总比滥情好
    2021-02-07 16:30

    Because S3 supports partial downloads, Chrome initially buffers "only what's needed" in front of the playhead and then stops buffering. It will continue buffering "only what's needed" when the video starts playing. This means that depending on the user's download speed it will stop buffering now and then, just because it has enough buffer to play continuously.

    But if you pause the video after having played some, Chrome will not stop buffering and go through all the way to the end.

    This example exploits that technique to entirely buffer the video off screen before showing it on the page.

    Tested on Chrome 32

    // Create video in background and start playing
    var video = document.createElement('video');
    video.src = 'video.mp4';
    video.controls = true;
    video.muted = true; 
    video.play();
    
    // Pause immediately after it starts playing.
    video.addEventListener("timeupdate", function() {
        if (this.currentTime > 0) {
    
            this.pause();
            video.muted = false;
            video.currentTime = 0
            this.removeEventListener("timeupdate", arguments.callee, false);
    
            // When whole video is buffered, show video on page
            video.addEventListener("progress", function() {
                if (Math.round(video.buffered.end(0)) / Math.round(video.seekable.end(0)) == 1) {
                    document.body.appendChild(video);
                    this.removeEventListener("progress", arguments.callee, false);
                }
            }, false);
        }
    }, false);
    

提交回复
热议问题