charleshawk
charleshawk

Reputation: 47

How to autoplay two HTML5 videos together after loading?

I'm trying to have two HTML5 videos autoplay at the exact same time. In other words, can I prevent these videos from playing until they have both loaded?

I don't want one to begin playing with the second is still loading. I hope this makes sense.

Upvotes: 3

Views: 1650

Answers (1)

Mick
Mick

Reputation: 25471

You can use the 'onloadeddata' function to check both have loaded, and then start both at the same time. I think you are at the mercy of the browser and JavaScript engine implementation for exactly how accurate the synching will be, but from quick testing this seems pretty synched so long as you are not worried about millisecond synch.

See below for an example.

var vid1 = document.getElementById("MyVid1");
var vid2 = document.getElementById("MyVid2");

var vid1Ready = false
var vid2Ready = false

vid1.onloadeddata = function() {
    if (vid2Ready == true) {
      vid1.play()
      vid2.play()
    } else {
      vid1Ready = true
    }
};

vid2.onloadeddata = function() {
    if (vid1Ready == true) {
      vid1.play()
      vid2.play()
    } else {
      vid2Ready = true
    }
};
<video id="MyVid1" width="320" height="176" controls preload="auto">
  <source src="http://ftp.nluug.nl/pub/graphics/blender/demo/movies/ToS/tears_of_steel_720p.mov" type="video/mp4">
  Your browser does not support this video format
</video>

<video id="MyVid2" width="320" height="176" controls preload="auto">
  <source src="http://peach.themazzone.com/durian/movies/sintel-1024-surround.mp4" type="video/mp4">
  Your browser does not support this video format
</video>

Upvotes: 1

Related Questions