JavaScript - How can I play multiple videos at once?

帅比萌擦擦* 提交于 2020-05-13 18:55:09

问题


I have an array of video elements that I wish to play at the same time.

The only way I've found online that I could do this would be to use new MediaController(); but that doesn't seem widely/if at all supported.

What I was expecting to do was:

var videos = document.querySelectorAll('video');
var mc = new MediaController();
video.forEach(function(el) {
    el.controller = mc;
});
mc.play();

The only way I've found to do this is doing a forEach on the array and playing them one after another, but I was wondering if anyone know if there might be a way to do this, but you notice a slight delay between video[0] and video[4] when playing.

Is it even possible to get this to be seemless with JavaScript?

P.S. This'll only need to be a Webkit solution as this isn't really something for a browser, but more for a front end for a UE4 game.


回答1:


My hypothesis is that they don't play at once because they are loading asynchronously. I would suggest to wait for ready state of all videos and then play them one by one. Here is an example of how you can achieve this with Promise.

// Get all videos.
var videos = document.querySelectorAll('video');

// Create a promise to wait all videos to be loaded at the same time.
// When all of the videos are ready, call resolve().
var promise = new Promise(function(resolve) {
  var loaded = 0;

  videos.forEach(function(v) {
    v.addEventListener('loadedmetadata', function() {
      loaded++;

      if (loaded === videos.length) {
        resolve();
      }
    });
  });
});

// Play all videos one by one only when all videos are ready to be played.
promise.then(function() {
  videos.forEach(function(v) {
    v.play();
  });
});
<video width="400" controls>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>

<video width="400" controls>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>

<video width="400" controls>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>


来源:https://stackoverflow.com/questions/46254716/javascript-how-can-i-play-multiple-videos-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!