Been trying to change the source video of an HTML5 video (after clicking a button). However I run into errors. Code and errors below:
Relevant HTML:
<video id="video2" playsinline controls muted preload="auto" style="z-index: -1; position: absolute;">
<source src="exercise_media/vid_exercise_sample_1.mp4" type="video/mp4" >
</video>
(regarding the z-index stuff - this video plays then is grabbed by a canvas which re-draws it, as part of the overall application. Probably not relevant but figured I'd mention it.)
Relevant Javascript. Initiates the video, plays it fine. It's a little esoteric because I started from someone else's sample.
loadCompanionVideo();
export async function loadCompanionVideo() {
setStatusText('Setting up companion video...');
try {
video2 = await loadVideo2();
} catch (e) {
let info = document.getElementById('info');
info.textContent = '(video player) this device type is not supported yet, ' +
'or this browser does not support video capture: ' + e.toString();
info.style.display = 'block';
throw e;
}
}
async function loadVideo2() {
const video2 = await setupVideo2();
return video2;
}
async function setupVideo2() {
const video2 = document.getElementById('video2');
video2.width = videoWidth2; // some external numbers
video2.height = videoHeight2; // just to customize width and height; works fine
return video2;
}
So this is fine, my first video exercise_media/vid_exercise_sample_1.mp4
plays just fine. However, I want to change the video source to exercise_media/vid_exercise_sample_2.mp4
, same format, located in same folder, etc. (I made sure this video is fine by hard-coding it into the HTML above, and it also plays just fine.)
Here's what I've been trying for changing it:
function buttonFunctionChangeVideoSrc() {
document.getElementById("video2").pause();
//document.getElementById("#video2 > source").src = "exercise_media/vid_exercise_sample_2.mp4";
document.getElementById("video2").src = "exercise_media/vid_exercise_sample_2.mp4";
document.getElementById("video2").load();
document.getElementById("video2").play();
}
To no avail, neither ("#video2 > source").src
nor ("video2").src
work. In the first case, the error is:
Uncaught TypeError: Cannot set property 'src' of null at HTMLButtonElement...
The video pauses and stays freezed.
In the second case, trying video2.src
directly (same as document.getElementById("video2")
), the error is
Uncaught (in promise) DOMException: Failed to load because no supported source was found.
The video portion of the screen goes white/blank.
Play/pause functionality works fine, so I know I have a valid reference to my video2
object. But I cannot seem to change the source. And I also know that the other source video works just fine, as I can hard-code it into the HTML and play it without issue. But I cannot seem to dynamically switch between them.
Any help is much appreciated.
from Not able to dynamically change source of the HTML5 Video with Javascript
No comments:
Post a Comment