I adapt a script to read random videos from a folder, The script works but still read the same video first, then start the 2nd random videos, I would like to read from the first random video
my script:
<script>
<?php
$directory = 'videos';
$path = './'.$directory.'/';
$allFiles = scandir($path,1);
$files = array_diff($allFiles, array('.'));
print_r($files)
?>
</script>
<video src="<?php echo './videos/'.$files[0];?>" id="myvideo" width="1280" height="720" controls autoplay playsinline style="background:black">
</video>
<script type='text/javascript'>
var directory = '<?php echo $directory;?>';
var myvids = <?php echo json_encode($files); ?>;
index=0;
document.getElementById('myvideo').addEventListener('ended',randomlyChooseVideo,false);
var activeVideo = getRandomIndex(myvids.length);
function getRandomIndex(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function randomlyChooseVideo() {
var vid = document.getElementById("myvideo");
vid.src = directory+'/'+myvids[activeVideo];
activeVideo = getRandomIndex(myvids.length);
}
</script>
I know that the problem is that the script requires reading the first video on the list "$files[0]" :
<video src="<?php echo './videos/'.$files[0];?>
But how can I do otherwise?
Edit:
2
Answers
I finally found a solution, so that it works as I wanted , here is my script:
You’re declaring the source on this line in a static variable:
vid.src = directory+’/’+myvids[activeVideo];
Don’t store the random index in activeVideo variable. Instead, turn activeVideo into a function, like so:
function activeVideo(){ return getRandomIndex(myvids.length) }
And make sure to add () to activeVideos inside randomlyChooseVideo, like so:
vid.src = directory+’/’+myvids[activeVideo()];