问题
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