dimanche 14 novembre 2021

How to randomly (and seamlessly) display several background videos on an endless loop using JavaScript

Here is what I want to achieve: I've got a bunch of clips in an array and I want all of them to be displayed randomly and seamlessly (using preload options) as background videos. I took some code that I found in another post and so far I've been able to make the first video to be chosen randomly, but then the rest of them keep displaying in order (as included in the array). How would you modified this code so all of them –and not only the first one– are displayed randomly? I guess it should be pretty easy to solve this problem to most of you but I am not a programmer so it would be great if any of you could help me. Thanks in advance. Here is my current code:

    <script>
        var videoContainer = document.getElementById('videoContainer'),
            output = document.getElementById('output'),
            nextVideo,
            videoObjects =
            [
                document.createElement('video'),
                document.createElement('video')
            ],
            vidSources =
            [
                "clip1.mov",
                "clip2.mov",
                "clip3.mov",
                "clip4.mov",
            ],
            nextActiveVideo = Math.floor((Math.random() * vidSources.length));
            
        videoObjects[0].inx = 0; 
        videoObjects[1].inx = 1;

        initVideoElement(videoObjects[0]);
        initVideoElement(videoObjects[1]);

        videoObjects[0].autoplay = true;
        videoObjects[0].src = vidSources[nextActiveVideo];
        videoContainer.appendChild(videoObjects[0]);

        videoObjects[1].style.display = 'none';
        videoContainer.appendChild(videoObjects[1]);

        function initVideoElement(video)
        {
            video.playsinline = true;
            video.muted = false;
            video.preload = 'auto';

            video.onplaying = function(e)
            {
                nextActiveVideo = ++nextActiveVideo % vidSources.length;

                if(this.inx == 0)
                    nextVideo = videoObjects[1];
                else
                    nextVideo = videoObjects[0];

                nextVideo.src = vidSources[nextActiveVideo];
                nextVideo.pause();
            };

            video.onended = function(e)
            {   
                this.style.display = 'none';
                nextVideo.style.display = 'block';
                nextVideo.play();
            };
        }
    </script>
<body>
        <div id="videoContainer"></div>
</body>
video {
    object-fit: cover;
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
}
#videoContainer {
    display: inline-block;
}



Aucun commentaire:

Enregistrer un commentaire