Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose random source for HTML5 video

I am running the following code which changes the source of an html5 video as soon as the initial source ends. After the first video finishes, it runs the second, then third and eventually starts again from the beginning, resulting in an endless cycle.

var myvid = document.getElementById('myvideo');
var myvids = [
  "http://www.w3schools.com/html/mov_bbb.mp4", 
  "http://www.w3schools.com/html/movie.mp4"
  ];
var activeVideo = 0;

myvid.addEventListener('ended', function(e) {
  // update the active video index
  activeVideo = (++activeVideo) % myvids.length;

  // update the video source and play
  myvid.src = myvids[activeVideo];
  myvid.play();
});
<video src="http://www.w3schools.com/html/mov_bbb.mp4" id="myvideo" width="320" height="240" autoplay muted playsinline style="background:black">
</video>

Now my question is: How can I randomize which of the videos in the javascript code comes first? I would like it to randomly choose one from the list, whenever the code is executed the first time. After choosing a random starting point, it should go through the list in the normal order. It shouldn't make every video random, only the starting point.

like image 221
Jascha Goltermann Avatar asked Sep 03 '25 16:09

Jascha Goltermann


1 Answers

You can try this :

function getRandomIndex(max) {
  /* The function will return a random number between 0 and max - 1 */
  return Math.floor(Math.random() * Math.floor(max));
}

function randomlyChooseVideo() {
  activeVideo = getRandomIndex(myvids.length);

  // update the video source and play
  myvid.src = myvids[activeVideo];
  myvid.play();
}

var myvid = document.getElementById('myvideo');
var myvids = [
  "http://www.w3schools.com/html/mov_bbb.mp4", 
  "http://www.w3schools.com/html/movie.mp4"
  ];
/* The initial active video will radomly be choosen between 0 and videoArray length - 1 */
var activeVideo = getRandomIndex(myvids.length);

window.onload = function(e) {
  randomlyChooseVideo()
}

myvid.addEventListener('ended', function(e) {
  randomlyChooseVideo()
});
<video src="" id="myvideo" width="320" height="240" autoplay muted playsinline style="background:black">
</video>
like image 198
Mohamed Sadat Avatar answered Sep 05 '25 08:09

Mohamed Sadat