Reputation: 653
I was wondering how to load two or more video or audio files at once, and then wait for them all to be ready before playing.
The current way I've listed below seems to work for the most part, however, this can sometimes not fully wait for both to be ready to play through (since the oncanplay method is attached to different videos sources). This can of course cause issues when I want multiple file types to be completely synchronized.
function loadSources() {
var videoOne = document.getElementById("first");
videoOne.src = "first-video.mp4";
var videoTwo = document.getElementById("second");
videoTwo.src = "second-video.mp4";
videoOne.oncanplay = function() {
videoOne.play();
};
videoTwo.oncanplay = function() {
videoTwo.play();
};
}
How would I go about combining multiple oncanplay events into one?
Upvotes: 1
Views: 394
Reputation: 890
One way to do this is by listening for a load
event on the elements and incrementing an integer as resources are loaded. It would look something like the following code:
const videoOne = document.getElementById("first");
let loaded = 0;
videoOne.addEventListener("load", () => {
if (loaded === RESOURCE_NUM - 1) { // resources required to be loaded
// play the video / audio files
}
else {
loaded++;
}
});
Upvotes: 2