HTML5 Video - Change multiple sources

99封情书 提交于 2019-11-30 05:59:58

问题


I have found several sites on Google about this problem and also found a few questions on here, which were apparently answered, but as I've been working on this for the last one or two weeks and just can't seem to get it to work at all, I wanted to revisit this.

I'm working on a demo that uses several video tags (vd1-3) which are then used in several canvas tags (cv1-3).

<video id="vd1" width="480" preload> 
    <source src="jerryclips/Bild01.webm" type="video/webm" id="vd1webm">
    <source src="jerryclips/Bild01.mp4" type="video/mp4" id="vd1mp4">
</video>

<canvas id="cv1" width="160" height="270"></canvas>

I got a working version that uses one video. Now I would like to be able to dynamically change the clips that are playing in my video tags and subsequently in the canvas tags. Changing only one source worked, as far as I remember that was just "vd1.src = '...'", but I want to have at least two video files in there. Now as you can see here, I tried using id's for the sources (as was suggested in an answered question here on stackoverflow), but I wasn't able to make that work.

We were able to get all the sources with this little bit of code here:

var x = document.getElementById("vd1");

var items = x.getElementsByTagName("source");

for(var i= 0; i < items.length; i++){
    alert(items[i].getAttribute('src'));
}
}, false);

But I also failed to use it in order to change my sources. I thought I might be able to use "items[i].src = ..." or use setAttribute, but I can't get anything to work.

I'm still fairly new to all this, so I'm possibly missing something very simple... so if anyone has an idea and could point me into a direction, I would really appreciate it.

Update: Eventually we came up with this solution which is pretty simple and straightforward

var videoPlaying = vd1.currentSrc;
var ext = videoPlaying.substr(videoPlaying.lastIndexOf("."));
vd1.src = "jerryclips/Bild02"+ext;

回答1:


I think you're overcomplicating things - there's no need to update multiple sources as any given browser is only ever going to be playing one of your videos. If you're loading new sources with JavaScript you can simply query the currentSrc property of vd1, determine which of the videos is playing and load the new video in that format. At that point I'd simply remove all the source elements and set video.src to the new value.



来源:https://stackoverflow.com/questions/5703203/html5-video-change-multiple-sources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!