I’m trying to make something like a video call interface, but I’m playing videos that get generated based on user responses. I need to be able to switch between the video currently displayed to the next generated video without the HTML collapsing and rebuilding the video element.
I tried just to change the source of the video using javascript and hoped that it would lead to a seamless transition, but that led to the video "collapsing" and then forming again.
The javascript looks something like this:
const video_html = document.getElementById('video');
function changeSource(path){
video_html.src = path;
}
2
Answers
The issue you’re encountering could be due to the browser not yet having loaded the video when you’re trying to switch its source.
You can use the loadedmetadata event, which is fired when the user agent can play the media, and estimates that if playback were to be started now, it would not need to stop for further buffering.See this for more info.
loadedmetadata_event mozilla developer
Like this
The natural state of the MPEG video decoder is to re-initialize for new data. This cannot be avoided so you need a workaround (and that depends on how advanced you are as a coder or video engineer).
(1) If all the video clips already exist, and need only to be dynamically selected…
Easiest: Switch between two video tags:
<video>
tags to hold a "now playing" and a "next playing" video.myvid.style.visibility = "hidden"
).z-index
,position
,top
,left
, to position one video tag above another.Easier: Seek to different clips within one video file:
timeupdate
event).(2) If the video clips are dynamically generated (eg: lip sync for custom response’s words)…
Harder: Use MediaSource Extensions to feed each video as a chunk:
Feeding in video bytes with MSE does not force the
<video>
tag to reload.It expects to be occasionally receiving video data so it stays "open" all the time.
An alternative to using MSE is to instead use PHP to feed video bytes into a
<video>
tag. This means using a.php
as video source instead of a.mp4
file.The MSE and PHP methods require you to know about MP4 file structure (is multiple byte-values inside an Array, and byte just means a number between 0 and 255). You need to learn which bytes represent your file’s header and which bytes are the audio/video frames.