0

I have a list of video URLs. My goal is to play each item one by one until all items inside the array are played. What I tried below kinda works but it's a really bad approach. What's a better way to play each source inside the array turn by turn? Thanks in advance.

myArr = ["http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4"]

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

(async() => {
  for (let i = 0; i < myArr.length; i++) {
    $('#video').attr('src', myArr[i])
    //wait until metadata is loaded
    await sleep(600)
    const duration = $('#video')[0].duration
    console.log(duration)
    $('#video').play()
    //wait until video finishes playing
    await sleep(duration);
  }
  console.log("done");
})();
video {
  width: 100%;
  height: 40vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<video id="video" src="" controls/>
seriously
  • 1,202
  • 5
  • 23

1 Answers1

1

When you go through every video in the array, you can wait for the "ended" event:

let video = document.getElementById('video');

video.addEventListener('ended', function() {
  //Next video stuff here...
});

You don`t need to work with jquery here. Pure JS will be as simple as your example :) Check out the MDN Reference for more video events: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended_event

Lukas
  • 408
  • 4
  • 10
  • do you mean await the ended event like ```async function test() { for (let i = 0; i < myArr.length; i++) { $('#video').attr('src', myArr[i]) $('#video').play() let video = document.getElementById('video'); var ended = await video.addEventListener('ended', function() { return 'video ended' }); } console.log("done"); }``` – seriously May 08 '23 at 13:34
  • 1
    You can help yourself by adding another parameter to your array and count through it. If every video is finished (every video returned the "ended" back) you can say console.log("done"); – Lukas May 08 '23 at 14:13