Changing the Source of an HTML5 Video Tag: A Comprehensive Solution
Creating a universal video player requires addressing the issue of dynamically changing the source of the video. This allows users to switch between videos in a playlist. While previous approaches using multiple
Identifying the File Type Using canPlayType():
To determine the appropriate file type for the video, we can utilize the canPlayType() function. This function returns a string indicating the browser's level of support for a given media type. For example:
var canPlayMP4 = video.canPlayType('video/mp4'); var canPlayWebM = video.canPlayType('video/webm');
Based on the results of canPlayType(), we can dynamically set the src attribute of the
Implementation Using Vanilla JavaScript:
Here's a code snippet demonstrating how to change the source of the video using vanilla JavaScript:
var video = document.getElementById('video'); // Create a new source element var source = document.createElement('source'); // Set the source attributes dynamically based on browser support if (canPlayMP4) { source.setAttribute('src', 'video.mp4'); source.setAttribute('type', 'video/mp4'); } else if (canPlayWebM) { source.setAttribute('src', 'video.webm'); source.setAttribute('type', 'video/webm'); } // Append the source to the video element video.appendChild(source); // Play the video video.play();
This approach allows for dynamic source switching without the drawbacks of using multiple
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3