简体   繁体   中英

How to keep synchronized video element especially after pause/play event in (html5/javascript)

I try to have in a html5 webpage project three elements fully synchronized. To ensure no shift due to video download, I put the attribute preload="auto" to the video elements.

My script is as follows:

    var run = document.getElementById("run"); //run is a button element
    var vid = document.getElementById("video1"); // the first video element

    function PlayVideo() {
        if (vid.paused) {
            vid.play();
            run.textContent = "||";
        } else {
            vid.pause();
            run.textContent = ">";
        }       
    } // The PlayVideo() function is called onclick on the run button

    $('#video1').on('play', ambiance = function(){
    document.getElementById("video2").play();
    document.getElementById("video3").play();       
    });

    $('#video1').on('pause', ambiance = function(){
    document.getElementById("video2").pause();
    document.getElementById("video3").pause();      
    });

When using this piece of script after waiting few seconds to a complete load of the video files, the run button plays correctly the first video and the two others start synchronized. But when I pause the run button pushing a second time on it, only the first video stops and the two others continue to be played during 2 or 3 seconds (both of them synchronized but not with the first one).

Could you help me? Is there an other way (more elegant) to play synchronized video?

One last element: the source of the three video is the same. (Same video played in each elements).

Thank you

Try something like this:

var videos = document.querySelectorAll('video');

function playAll() {
  [].forEach.call(videos, function(video) {
     video.play()
  });
}

function pauseAll() {
  [].forEach.call(videos, function(video) {
     video.pause()
  });
}

// this keeps everything synchronized
[].forEach.call(videos, function(video) {
  video.addEventListener('play', playAll, false);
  video.addEventListener('pause', pauseAll, false);
});

Keep in mind there will probably still be a slight offset (if you have sound it'll sound distorted)

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