javascriptjquery

How can I ensure that 2 <video>s are played at the exact same time (with no lag)?


Here is my current code: https://jsfiddle.net/n7u4twb1/10/

Current js code:

Data={
  num_files:2
}

Video = {
  preview: {
    play_all: function(){
      for(i=0;i<Data.num_files;i++){
         $('#video'+i).get(0).play();
      }
    }
  }
}

With the "Play All" button I encounter lag more than half the time. How can I ensure that the videos are played at the same time with no lag? It is to preview video collages (multiple videos) before they are processed and turned into one video -- I want users to be able to edit the timing at which each video starts but they need a way to preview the collage before the processing starts! Thanks in advance


Solution

  • If you have a button for each video, add an extra button that uses the .click() method. The .click() method is like jQuery .trigger() method which when invoked will auto click whatever it's bound to.

    Demo

    var ui = document.forms.ui;
    var btns = ui.elements;
    
    btns[0].onclick = function(e) {
      play(0);
    }
    
    btns[1].onclick = function(e) {
      play(1);
    }
    
    btns.vSync.onclick = function(e) {
      btns[0].click();
      btns[1].click();
    }
    
    function play(idx) {
      var vids = Array.from(document.querySelectorAll('video'));
      var vid = vids[idx];
      if (vid.paused || vid.ended) {
        vid.play();
      } else {
        vid.pause();
      }
    }
    <video src='https://glsec.s3.amazonaws.com/mp4/60s.mp4' width='240'></video>
    <video src='https://glsec.s3.amazonaws.com/mp4/60s.mp4' width='240'></video>
    
    <form id='ui'>
      <button data-id='0' type='button'>VIDEO A</button>
      <button data-id='1' type='button'>VIDEO B</button>
      <button id='vSync' type='button'>SYNC</button>
    </form>