如何在网站上两次显示相同的HTML 5视频而不加载两次?

时间:2014-06-30 18:29:31

标签: javascript html html5 video

我目前在html页面上有2个视频元素 两者都嵌入了来自同一网址的完全相同的.mp4视频。

有没有办法告诉浏览器从第一个视频元素复制渲染视频而不是让浏览器下载两个视频?

您可以清楚地看到这两个视频是分开加载的,因为它们在播放前有不同的缓冲时间,而且每次视频都不会同步播放。

我的代码:

<video autoplay id="previewVideo" data-videoid="JYpUXXD4xgc">
    <source src="video.php?videoid=JYpUXXD4xgc" type="video/mp4"/>
</video>

<video autoplay id="bigVideo"     data-videoid="JYpUXXD4xgc">
    <source src="video.php?videoid=JYpUXXD4xgc" type="video/mp4"/>
</video>

3 个答案:

答案 0 :(得分:8)

这可以通过Javascript和Canvas元素在一些非常简单的步骤中完成:

HTML:

<video autoplay id="previewVideo" data-videoid="JYpUXXD4xgc">
    <source src="video.php?videoid=JYpUXXD4xgc" type="video/mp4"/>
</video>    
<canvas id="bigVideo"></canvas>

使用Javascript:

document.addEventListener('DOMContentLoaded', function(){
  var v = document.getElementById('previewVideo');
  var canvas = document.getElementById('bigVideo');
  var context = canvas.getContext('2d');
  var cw = Math.floor(canvas.clientWidth);
  var ch = Math.floor(canvas.clientHeight);
  canvas.width = cw;
  canvas.height = ch;
  v.addEventListener('play', function(){
      updateBigVideo(this,context,cw,ch);
  },false);
},false);


function updateBigVideo(v,c,w,h) {
    if(v.paused || v.ended) return false;
    c.drawImage(v,0,0,w,h);
    setTimeout(updateBigVideo,20,v,c,w,h);
}

画布获取视频图像并在BigVideo上再次显示 每20ms调用updateBigVideo()函数,结果帧速率约为50 FPS。

在此处阅读更多内容:http://html5doctor.com/video-canvas-magic/

答案 1 :(得分:1)

首先,使用JavaScript制作<video>元素,然后将其放在您想要的位置。

var video1 = document.createElement("video");
video1["data-videoid"] = "JYpUXXD4xgc";
var sourceElem = document.createElement("source");
sourceElem.src = "video.php?videoid=JYpUXXD4xgc";
sourceElem.type = "video/mp4";
video1.appendChild(sourceElem);

var video2 = video1.cloneNode(true); //This makes a copy of the element, but makes sure it's not treated as the same element. This means you can add video1 AND this _different_ element to the document. However, unfortunately, everything still needs to get loaded again. I think this is the easiest way to copy an element over, though.
video2.id = "bigVideo";
video1.id = "previewVideo";

document.addEventListener("DOMContentLoaded", function() {
    //Now put video1 and video2 where you want.
});

答案 2 :(得分:0)

一个简单的解决方案是使用#anything

将值添加到网址的末尾

由于您要将视频加载到一个视频元素中,并希望在不同的视频元素中再次加载视频,因此您可以使用唯一网址将其排列如下:

<video autoplay id="mainVideo">
    <source src="video.php?videoid=JYpUXXD4xgc&item=1" type="video/mp4"/>
</video>

<video autoplay id="previewVideo">
    <source src="video.php?videoid=JYpUXXD4xgc&item=2" type="video/mp4"/>
</video>