Changing Video Source
Related Specification |
Main Reason |
Applies to |
---|---|---|
readyState, HTMLMediaElement |
webOS TV v3.0 and later |
Backward Compatible Code
Before changing the source element, you need to consider the readyState status. We recommend using the load() method for initiating readyState as below:
// JavaScript Code function changeSource() { var vidElement = document.getElementById("myVideo"); // Remove all source elements while (vidElement.firstChild) vidElement.removeChild(vidElement.firstChild); // Initiating readyState of HTMLMediaElement vidElement.load(); // Add new source element var source = document.createElement("source"); source.setAttribute('src','./video/multi-soundtrack.mp4'); source.setAttribute('type','video/mp4'); vidElement.appendChild(source); } <!-- HTML Code --> ... <video id="myVideo"> <source src="./video/oceans-clip.mp4" type="video/mp4" /> </video>
Why Use This Code?
The source element is used for playing MPEG, HLS, and DRM format content. According to the HTML5 specification, if the readyState of HTMLMediaElement is not HAVE_NOTHING, the source element cannot be changed or removed. During the video playback, readyState is usually set to a value other than HAVE_NOTHING. However, WebKit used on webOS TV v1.x and v2.0 does not support readyState and keeps the readyState value to HAVE_NOTHING (NULL). With the release of webOS TV v3.0, WebKit is replaced by Blink, which fully supports readyState.
You have probably replaced the source element to change the video content, similar to below. However, this code does not work anymore since webOS TV 3.0.
// JavaScript Code function changeSource() { var vidElement = document.getElementById("myVideo"); // Remove all source elements while (vidElement.firstChild) vidElement.removeChild(element.firstChild); // Add a new source element var source = document.createElement("source"); source.setAttribute('src','./video/multi-soundtrack.mp4'); source.setAttribute('type','video/mp4'); vidElement.appendChild(source); } <!-- HTML Code --> ... <video id="myVideo"> <source src="./video/oceans-clip.mp4" type="video/mp4" /> </video>