网站搜索

html - 无法使用 Javascript 动态更改 HTML5 视频的源


一直在尝试更改 HTML5 视频的源视频(点击按钮后)。但是我遇到了错误。以下是代码和错误:

相关的 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>

(关于 z-index 的问题——这个视频先播放,然后被一个画布捕捉并重新绘制,作为整个应用程序的一部分。可能不相关,但我觉得我还是提一下。)

相关的 Javascript。初始化视频,播放正常。有点难懂,因为我是从别人的示例开始的。

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;
  
}

所以这个没问题,我的第一个视频 exercise_media/vid_exercise_sample_1.mp4 播放得很好。不过,我想把视频源改成 exercise_media/vid_exercise_sample_2.mp4,格式相同,位于同一文件夹等。(我通过将这个视频硬编码到上面的 HTML 中确认过视频没问题,它播放也没问题。)

这是我一直在尝试改变它的方法:

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();
    
}

无济于事,("#video2 > source").src 和 ("video2").src 都不起作用。在第一种情况下,错误是:

未捕获的类型错误:无法设置 null 的 'src' 属性,发生在 HTMLButtonElement。视频暂停并保持冻结状态。

在第二种情况下,直接尝试 video2.src(与 document.getElementById("video2") 相同),错误是

未捕获(在 promise 中)DOM 异常:加载失败,因为未找到支持的来源。

视频屏幕部分变白/空白。

播放/暂停功能正常,所以我知道我对我的 video2 对象有有效的引用。但我似乎无法更改视频源。我也知道另一个源视频工作正常,因为我可以将其硬编码到 HTML 中并播放它而没有问题。但我似乎无法在它们之间动态切换。

任何帮助都非常感激。


添加更多我的代码供查看。不要担心姿势的东西,这是我的应用程序用来分析视频的,当我只是将一个视频与摄像头并排显示时它工作得很好(这就是我的应用程序所做的)。

问题是我无法将 video2 的源更改为不同的 MP4。实际上,我能让它播放 MP4 的唯一方法就是在 HTML 中明确设置它。

HTML :

<div id="canvases" class="canvas-container">
        <div id='main' style='display:none'>
            <video id="video" playsinline style=" -moz-transform: scaleX(-1);
            -o-transform: scaleX(-1);
            -webkit-transform: scaleX(-1);
            transform: scaleX(-1);
            display: none;
            ">
            </video>
            <canvas id="output" class="camera-canvas"></canvas>
            <canvas id="keypoints" class="camera-canvas"></canvas>
            
            <video id="video2" playsinline controls muted style="z-index: -1; position: absolute;" 
            >
            <source id="source2" src="exercise_media/vid_exercise_sample_1.mp4" type="video/mp4"  > 
<!-- hard-coding the src in source is the ONLY way I can play a video here at all...  --> 

            </video>
            
            <canvas id="output2" class="camera-canvas2"></canvas>
            <canvas id="keypoints2" class="camera-canvas2"></canvas>

        <canvas class="illustration-canvas"></cavnas>
        <canvas class="illustration-canvas2"></cavnas>

    </div>

Javascript :

export async function bindPage() {
  setupCanvas();
  setupCanvas2();
  buttonSetup();
  toggleLoadingUI(true);
  setStatusText('Loading AI models...');
  posenet = await posenet_module.load({
    architecture: defaultPoseNetArchitecture,
    outputStride: defaultStride,
    inputResolution: defaultInputResolution,
    multiplier: defaultMultiplier,
    quantBytes: defaultQuantBytes
  });
  setStatusText('Loading FaceMesh model...');
  facemesh = await facemesh_module.load();
  facemesh2 = await facemesh_module.load();
  setStatusText('Loading Avatar file...');
  let t0 = new Date();
  await parseSVG(Object.values(avatarSvgs)[0]);

  setStatusText('Setting up camera...');
  try {
    video = await loadVideo();
  } catch (e) {
    let info = document.getElementById('info');
    info.textContent = '(web cam) this device type is not supported yet, ' +
      'or this browser does not support video capture: ' + e.toString();
    info.style.display = 'block';
    throw e;
  }
  
  try {
    video2 = await loadVideo2();
  } catch (e) {
    console.log("Error loading companion video :: "+e);
  }
  console.log(video2); // shows the full html
  playpauseFunction(); // start video2
  
  toggleLoadingUI(false);
  
  detectPoseInRealTime(video, posenet); //actual application, works fine
  
}

async function loadVideo2() {
  const video2 = await setupVideo2();
  return video2;
}

async function setupVideo2() {
  
  const video2 = document.getElementById('video2');
  
  //video2.setAttribute("src", vid_url_1); //does not work 
  //document.getElementById("source2").src = vid_url_2; // does nothing
  
  videoWidth2orig = video2.videoWidth;
  videoHeight2orig = video2.videoHeight; // gives the actual e.g. 640 x 360
  //.. I do some stuff below to set video2 width/height, works fine
  
  return video2;
  
}

function playpauseFunction() {
    try {
        if (playpause == true) {
            video2.pause();
            playpause = false;
            //alert("Workout paused. Click Play/Pause to resume.");
        } else if (playpause == false) {
            video2.play();
            playpause = true;
        }   
    } catch (e) {
        console.log("playpauseFunction exception :: "+e);
    }
}

现在,正如我所说,如果我将 <source> 标签的 src 硬编码到 HTML 中,即 <source id="source2" src="exercise_media/vid_exercise_sample_1.mp4" type="video/mp4">,应用程序运行正常,看起来如下所示:

(运行良好,网络摄像头与视频实时播放,并且当视频播放时,我的骨骼跟踪在右侧视频上运行。)

我想做的是点击例如“练习示例 2”,并显然地更改右侧的视频。我尝试的任何方法都没有成功,例如:

function setupExercise2() {
    
    video2.setAttribute('autoplay', 'true');

    document.getElementById("source2").src = "exercise_media/vid_exercise_sample_2.mp4";
    //video2.setAttribute("src", "exercise_media/vid_exercise_sample_2.mp4"); // have tried both, neither work
    video2.load();

    const playPromise = video2.play()  // trigger video load

    console.log(playPromise); 

    if ( playPromise !== undefined ) {
       playPromise.then(() => {
          // video should start playing as soon as it buffers enough
       }).catch(error => {
          // playback failed, log error
          console.log(error);
       })
    }

}

特别是针对第一行(未被注释的),控制台显示:

Promise {<pending>}__proto__: Promise[[PromiseState]]: "pending"[[PromiseResult]]: undefined

右侧视频变成白色,什么也不播放。如果我改为取消注释 video2.setAttribute 行,则控制台会记录:

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: DOMException: Failed to load because no supported source was found.
code: 9
message: "Failed to load because no supported source was found."
name: "NotSupportedError"
__proto__: DOMException

明确一点,我可以将任何 vid_exercise_sample_{2,3,..}.mp4 硬编码到 HTML 中,它们都能正常播放和运行,所以我不认为问题出在这里。

希望我现在已经提供了一个相当完整的情况!

答案#1

以下示例代码显示了视频 .src 动态更新。
有两个按钮用于在不同的源之间切换。

它已经在 Windows 电脑上使用 Chrome、Edge 和 Firefox 浏览器进行了测试。

<!DOCTYPE html>
<html><head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> </head>

<body>

<video id="video2" width="600" height="480" controls style="z-index: 1; overflow:hidden; position: absolute; top: 10px; left: 10px">
<source type="video/mp4">
</video>

<canvas id="myCanvas" width="600" height="480" style="z-index: 1; overflow:hidden; position: absolute; top: 10px; left: 640px">
</canvas>

<div style="z-index: 1; overflow:hidden; position: absolute; top: 510px; left: 10px">
<button onclick="ChangeVideoSrc( 1 )">Play Video 1</button>
<button onclick="ChangeVideoSrc( 2 )">Play Video 2</button>
</div>

<script>

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var timer_DrawCanvas; //# updated later in code

//# Example video links that work on my testing...
vid_url_1 = "https://seed191.bitchute.com/pupNZR0eMW9M/4CU38o2lkgyj.mp4";
vid_url_2 = "https://seed171.bitchute.com/VBdNMrOHylJh/2BMyQPl6BSpZ.mp4";

//# Try your own links if the above works...
//vid_url_1 = "exercise_media/vid_exercise_sample_1.mp4"
//vid_url_2 = "exercise_media/vid_exercise_sample_2.mp4"

//# Set initial starting vid SRC (used on page load)
const myVid = document.getElementById("video2");
myVid.setAttribute("src", vid_url_1);

//# Setup event listeners
myVid.addEventListener("canplay", handle_Media_Events);
myVid.addEventListener("loadeddata", handle_Media_Events);
myVid.addEventListener("play", handle_Media_Events);
myVid.addEventListener("pause", handle_Media_Events);
myVid.addEventListener("ended", handle_Media_Events);

function drawVideo() 
{
    ctx.drawImage(myVid, 0, 0, 600, 480);
}

function ChangeVideoSrc( vidNum ) 
{
    myVid.src = window[ "vid_url_" + vidNum ];
    myVid.load();
}

function handle_Media_Events()
{
    //# if enough data to begin playback
    if ( event.type == "canplay" ) { myVid.play(); }
    
    //# if first frame is available
    if ( event.type == "loadeddata" ) 
    { ctx.drawImage( myVid, 0, 0, 600, 480 ); } //# draws re-sized
    
    if ( event.type == "play" )
    { timer_DrawCanvas = setInterval( drawVideo, 30 ); }
    
    if ( (event.type == "pause") || (event.type == "ended") )
    { clearInterval( timer_DrawCanvas ); }
    
}

</script>

</body>
</html>

希望这能为你实现《使用 Javascript 动态更改 HTML5 视频源》的任务提供一个参考点。任务仍在继续…

当你有机会测试代码时,随时提问。

答案#2

刚试了一个小片段,运行得很顺利.. 真奇怪..

我用过的

const v = document.getElementById("vid");
const s = document.getElementById("src");

function changeVideo() { 
   s.src = 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4';
   v.load();
   v.play();
   console.log(s,v);
}

document.getElementById("change").onclick=changeVideo;
<video id="vid" controls autoplay style="width:75%">
   <source id="src" src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4" type="video/mp4">
</video><br/><br/>
<button id="change">Change the video</button>

一定是缺少了什么。如果我看到一个活生生的例子,我就能确定地说,但那完全取决于你。

否则在 W3 上找到了这个

警告:不要使用 async 关键字将你的函数设为异步。你将失去允许视频稍后播放所需的“用户手势令牌”。