Home  >  Article  >  Web Front-end  >  How to Dynamically Change Video Source in HTML5 for Seamless Playlist Playback?

How to Dynamically Change Video Source in HTML5 for Seamless Playlist Playback?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 07:24:02743browse

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 tags and the load() method.

Solution:

To resolve this issue, rather than using multiple tags, you can determine the appropriate video file using the canPlayType() function and set the src attribute of the

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 tags and ensures compatibility across various browsers. Here's an example to illustrate the dynamic source change:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn