Home > Article > Web Front-end > How to Dynamically Change Video Source in HTML5 for Seamless Playlist Playback?
Dynamically Changing Video Source in HTML5
Problem:
You're aiming to create a comprehensive video player that supports playlist functionality and allows users to switch between videos seamlessly. To achieve this, you need to dynamically change the source of the HTML5 video tag using JavaScript. However, you're encountering issues in Firefox where the video player malfunctions when using multiple
Solution:
To resolve this issue, rather than using multiple
const video = document.querySelector('video'); // Check browser support for video formats const supportedFormat = video.canPlayType('video/mp4') ? 'mp4' : 'webm'; // Set video source based on supported format video.src = `my-video.${supportedFormat}`;
This approach eliminates the need for multiple
const video = document.querySelector('video'); const playlist = ['video1.mp4', 'video2.webm', 'video3.mp4']; // Current video index let currentVideoIndex = 0; // Function to load and play the next video in the playlist const loadNextVideo = () => { if (currentVideoIndex < playlist.length) { const videoPath = playlist[currentVideoIndex]; video.src = videoPath; video.load(); video.play(); currentVideoIndex++; } else { // Playlist completed, handle accordingly } }; // Event listener for onended event video.addEventListener('ended', loadNextVideo);
By dynamically changing the src attribute and using event listeners to control the playlist, you can achieve seamless playback without relying on Flash or external players. This approach provides greater control and flexibility in managing your video content.
The above is the detailed content of How to Dynamically Change Video Source in HTML5 for Seamless Playlist Playback?. For more information, please follow other related articles on the PHP Chinese website!