Skip to content

Commit

Permalink
dynamic mp4 background play upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
aleatorydialogue committed Jun 29, 2024
1 parent a2423a9 commit b5e9953
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
5 changes: 1 addition & 4 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,6 @@
</nav>
</div>
</footer>
<video autoplay muted loop id="bgVideo" playsinline>
<source src="backgrounds/2.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script src="scripts.js"></script>
</body>
</html>
43 changes: 43 additions & 0 deletions scripts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
function playVideo() {
var videos = [
'backgrounds/1.mp4',
'backgrounds/2.mp4',
'backgrounds/3.mp4',
'backgrounds/4.mp4',
'backgrounds/5.mp4'
];
var randomIndex = Math.floor(Math.random() * videos.length);
var randomVideo = videos[randomIndex];
var videoElement = document.createElement('video');
videoElement.setAttribute('autoplay', '');
videoElement.setAttribute('muted', '');
videoElement.setAttribute('loop', '');
videoElement.setAttribute('id', 'bgVideo');
videoElement.setAttribute('playsinline', '');
videoElement.setAttribute('preload', 'auto');
videoElement.muted = true; // Ensure muted is set programmatically as well
var sourceElement = document.createElement('source');
sourceElement.setAttribute('src', randomVideo);
sourceElement.setAttribute('type', 'video/mp4');
videoElement.appendChild(sourceElement);
document.body.appendChild(videoElement);

// Try to play as soon as possible
var playAttempt = setInterval(() => {
videoElement.play().then(() => {
clearInterval(playAttempt);
}).catch(error => {
console.log('Error attempting to play the video:', error);
});
}, 3000);

// Additional attempt when the video can play through
videoElement.addEventListener('canplaythrough', () => {
videoElement.play().catch(error => {
console.log('Error attempting to play on canplaythrough:', error);
});
});
}

// Call playVideo when the page loads
window.addEventListener('load', playVideo);

0 comments on commit b5e9953

Please sign in to comment.