简体   繁体   中英

Play inline html5 video smoothly by preloading video entirely

I have a 45 second video that I was able to compress to 4 Mo. I want the video to play smoothly and with autoplay, but it doesn't need to launch quickly as long as the poster image is present. So once it is fully loaded it should automatically play. I found this bit of javascript code but I am getting errors and I don't understand why.

<div class="video-container">
<video id="myvideo" controls autoplay muted poster="image.jpg" playsinline style="width: 100% !important;">
</video> </div>

<script type="text/javascript">
      var req = new XMLHttpRequest();
req.open('GET', 'example.com/wp-content/uploads/2019/07/video.mp4', true);
req.responseType = 'blob';
req.onload = function() {
// Onload is triggered even on 404
// so we need to check the status code
if (this.status === 200) {
  var videoBlob = this.response;
  var vid = URL.createObjectURL(videoBlob); // IE10+
  // Video is now downloaded
  // and we can set it as source on the video element
  video.src = vid;
}
}
req.onerror = function() {
// Error
}
req.send();
document.getElementById("myvideo").src = vid; 
</script>

I am getting the error that the video is not defined on the line video.src = vid; and subsequently on the line document.getElementById("myvideo").src = vid;

In the Console the video has correctly been charged to the page, between 1 to 3 seconds of upload.

There are different ways to achieve smooth(er) playback, the way I've had luck with is

    <video id="video" preload="auto" src="file.mp4" controls></video>

Setting the preload attribute to auto indicates that the browser may cache enough data that complete playback is possible without requiring a stop for further buffering.

The above example only preloads a couple of seconds so that the video can play smoothly without stopping to buffer, if you would like to preload the whole video before playback you could consult this example snippet

  <video id="video" controls></video>

  <script>
    // Later on, after some condition has been met, set video source to the
    // preloaded video URL.
    video.src = 'https://cdn.com/small-file.mp4';
    video.play().then(_ => {
    // If preloaded video URL was already cached, playback started 
    //immediately.
     });
    </script>

Source : https://developers.google.com/web/fundamentals/media/fast-playback-with-video-preload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM