trying to add a multi source video player with more then one video?

痞子三分冷 提交于 2019-12-10 11:49:39

问题


Im trying to make a video player work in all browsers. There is more then one video and every time you click on demo reel it plays the video and if you click the video 1 the other video plays. How can i make them both work in all browsers? Here is my html and javascript

html

<video id="myVideo" controls autoplay></video>
    <div>
        <a href="#" onClick="changeVid1();">Demo Reel</a></div>
    <a href="#" onClick="changeVid2();">video 1</a></div>

    </div>

javascript

function changeVid1() {
    var changeStuff = document.getElementById("myVideo");
     changeStuff.src = "video/demoreel.mp4"

}

function changeVid2() {
    var changeStuff = document.getElementById("myVideo");
     changeStuff.src = "video/video1.mp4";

}

回答1:


After you switch the source of the video, you need to run .load() on it to force it to load the new file. Also, you need to provide multiple formats, because there is no video codec supported by all browsers.

First, set up your sources like this:

var sources = [
    {
        'mp4': 'http://video-js.zencoder.com/oceans-clip.mp4',
        'webm':'http://video-js.zencoder.com/oceans-clip.webm',
        'ogg':'http://video-js.zencoder.com/oceans-clip.ogv'
    }
    // as many as you need...
];

Then, your switch function should look like this:

function switchVideo(index) {
    var s = sources[index], source, i;
    video.innerHTML = '';
    for (i in s) {
        source = document.createElement('source');
        source.src = s[i];
        source.setAttribute('type', 'video/' + i);
        video.appendChild(source);
    }
    video.load();
    video.play(); //optional
}

See a working demo here.

This gives the browser a list of different formats to try. It will go through each URL until it finds one it likes. Setting the "type" attribute on each source element tells the browser in advance what type of video it is so it can skip the ones it doesn't support. Otherwise, it has to hit the server to retrieve the header and figure out what kind of file it is.

This should work in Firefox going back to 3.5 as long as you provide an ogg/theora file. And it will work in iPads, because you only have one video element on the page at a time. However, auto-play won't work until after the user clicks play manually at least once.

For extra credit, you can append a flash fallback to the video element, after the source tags, for older browsers that don't support html5 video. (i.e., IE < 9 - though you'll need to use jQuery or another shim to replace addEventListener.)



来源:https://stackoverflow.com/questions/13682586/trying-to-add-a-multi-source-video-player-with-more-then-one-video

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