Javascript 更改 html5 视频标签上的源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5235145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:17:21  来源:igfitidea点击:

changing source on html5 video tag

javascripthtmlvideoload

提问by sashn

i'm trying to build a video player, that works everywhere. so far i'd be going with:

我正在尝试构建一个适用于任何地方的视频播放器。到目前为止,我会选择:

<video>
    <source src="video.mp4"></source>
    <source src="video.ogv"></source>
    <object data="flowplayer.swf" type="application/x-shockwave-flash">
        <param name="movie" value="flowplayer.swf" />
        <param name="flashvars" value='config={"clip":"video.mp4"}' />
    </object>
</video>

(as seen on several sites, for example video for everybody) so far, so good.

(如在几个网站上看到的,例如每个人的视频)到目前为止,很好。

but now i also want some kind of playlist/menu along with the video player, from which i can select other videos. those should be opened within my player right away. so i will have to "dynamically change the source of the video" (as seen on dev.opera.com/articles/everything-you-need-to-know-html5-video-audio/- section "Let's look at another movie") with javascript. let's forget about the flashplayer (and thus IE) part for the time being, i will try to deal with that later.

但现在我还想要某种播放列表/菜单以及视频播放器,我可以从中选择其他视频。这些应该立即在我的播放器中打开。所以我将不得不“动态更改视频的来源”(如dev.opera.com/articles/everything-you-need-to-know-html5-video-audio/部分“让我们看另一部电影” ") 使用 javascript。让我们暂时忘记 flashplayer(以及 IE)部分,稍后我将尝试处理它。

so my JS to change the <source>tags should be something like:

所以我的 JS 来改变<source>标签应该是这样的:

<script>
function loadAnotherVideo() {
    var video = document.getElementsByTagName('video')[0];
    var sources = video.getElementsByTagName('source');
    sources[0].src = 'video2.mp4';
    sources[1].src = 'video2.ogv';
    video.load();
}
</script>

problem is, this doesnt work in all browsers. namely, firefox =O there is a nice page, where you can observe the problem i'm having: http://www.w3.org/2010/05/video/mediaevents.html

问题是,这不适用于所有浏览器。即 firefox =O 有一个不错的页面,您可以在其中观察我遇到的问题:http: //www.w3.org/2010/05/video/mediaevents.html

as soon as i trigger the load() method (in firefox, mind you), the video player dies.

一旦我触发 load() 方法(在 Firefox 中,请注意),视频播放器就会死亡。

now i have found out that when i don't use multiple <source>tags, but instead just one src attribute within the <video>tag, the whole thing DOES work in firefox.

现在我发现当我不使用多个<source>标签,而是在<video>标签中只使用一个 src 属性时,整个事情都可以在 firefox 中工作。

so my plan is to just use that src attribute and determine the appropriate file using the canPlayType()function.

所以我的计划是只使用该 src 属性并使用canPlayType()函数确定适当的文件。

am i doing it wrong somehow or complicating things??

是我做错了什么还是让事情复杂化了??

回答by mattdlockyer

I hated all these answers because they were too short or relied on other frameworks.

我讨厌所有这些答案,因为它们太短或依赖于其他框架。

Here is "one" vanilla JS way of doing this, working in Chrome, please test in other browsers:

这是执行此操作的“一种”vanilla JS 方式,可在 Chrome 中使用,请在其他浏览器中测试:

http://jsfiddle.net/mattdlockyer/5eCEu/2/

http://jsfiddle.net/mattdlockyer/5eCEu/2/

HTML:

HTML:

<video id="video" width="320" height="240"></video>

JS:

JS:

var video = document.getElementById('video');
var source = document.createElement('source');

source.setAttribute('src', 'http://www.tools4movies.com/trailers/1012/Kill%20Bill%20Vol.3.mp4');

video.appendChild(source);
video.play();

setTimeout(function() {  
    video.pause();

    source.setAttribute('src', 'http://www.tools4movies.com/trailers/1012/Despicable%20Me%202.mp4'); 

    video.load();
    video.play();
}, 3000);

回答by Marius Engen Haugen

Modernizrworked like a charm for me.

Modernizr对我来说就像一种魅力。

What I did is that I didn't use <source>. Somehow this screwed things up, since the video only worked the first time load() was called. Instead I used the source attribute inside the video tag -> <video src="blabla.webm" />and used Modernizrto determine what format the browser supported.

我所做的是我没有使用<source>. 不知何故,这把事情搞砸了,因为视频只在第一次调用 load() 时工作​​。相反,我使用了 video 标签中的 source 属性 -><video src="blabla.webm" />并使用Modernizr来确定浏览器支持的格式。

<script>
var v = new Array();

v[0] = [
        "videos/video1.webmvp8.webm",
        "videos/video1.theora.ogv",
        "videos/video1.mp4video.mp4"
        ];
v[1] = [
        "videos/video2.webmvp8.webm",
        "videos/video2.theora.ogv",
        "videos/video2.mp4video.mp4"
        ];
v[2] = [
        "videos/video3.webmvp8.webm",
        "videos/video3.theora.ogv",
        "videos/video3.mp4video.mp4"
        ];

function changeVid(n){
    var video = document.getElementById('video');

    if(Modernizr.video && Modernizr.video.webm) {
        video.setAttribute("src", v[n][0]);
    } else if(Modernizr.video && Modernizr.video.ogg) {
        video.setAttribute("src", v[n][1]);
    } else if(Modernizr.video && Modernizr.video.h264) {
        video.setAttribute("src", v[n][2]);
    }

    video.load();
}
</script>

Hopefully this will help you :)

希望这会帮助你:)

If you don't want to use Modernizr, you can always use CanPlayType().

如果您不想使用Modernizr,您可以随时使用CanPlayType()

回答by greg.kindel

Your original plan sounds fine to me. You'll probably find more browser quirks dealing with dynamically managing the <source>elements, as indicated here by the W3 spec note:

你最初的计划对我来说听起来不错。您可能会发现更多处理动态管理<source>元素的浏览器怪癖,如 W3 规范说明所示:

Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unncessarily[sic] complicated approach.

当元素已经插入到视频或音频元素中时,动态修改源元素及其属性将不起作用。要更改正在播放的内容,只需直接使用媒体元素上的 src 属性,可能会使用 canPlayType() 方法从可用资源中进行选择。通常,在解析文档后手动操作源元素是一种不必要的复杂方法。

http://dev.w3.org/html5/spec/Overview.html#the-source-element

http://dev.w3.org/html5/spec/Overview.html#the-source-element

回答by Joaquin Iurchuk

I solved this with this simple method

我用这个简单的方法解决了这个问题

function changeSource(url) {
   var video = document.getElementById('video');
   video.src = url;
   video.play();
}

回答by Stephen Walcher

Instead of getting the same video player to load new files, why not erase the entire <video>element and recreate it. Most browsers will automatically load it if the src's are correct.

与其让相同的视频播放器加载新文件,不如擦除整个<video>元素并重新创建它。如果 src 正确,大多数浏览器会自动加载它。

Example (using Prototype):

示例(使用Prototype):

var vid = new Element('video', { 'autoplay': 'autoplay', 'controls': 'controls' });
var src = new Element('source', { 'src': 'video.ogg', 'type': 'video/ogg' });

vid.update(src);
src.insert({ before: new Element('source', { 'src': 'video.mp4', 'type': 'video/mp4' }) });

$('container_div').update(vid);

回答by Yaur

According to the spec

根据规范

Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unncessarily complicated approach.

当元素已经插入到视频或音频元素中时,动态修改源元素及其属性将不起作用。要更改正在播放的内容,只需直接使用媒体元素上的 src 属性,可能会使用 canPlayType() 方法从可用资源中进行选择。通常,在解析文档后手动操作源元素是一种不必要的复杂方法。

So what you are trying to do is apparently not supposed to work.

所以你试图做的显然不应该工作。

回答by Jose Antonio Galeano

Just put a div and update the content...

只需放置一个 div 并更新内容...

<script>
function setvideo(src) {
    document.getElementById('div_video').innerHTML = '<video autoplay controls id="video_ctrl" style="height: 100px; width: 100px;"><source src="'+src+'" type="video/mp4"></video>';
    document.getElementById('video_ctrl').play();
}
</script>
<button onClick="setvideo('video1.mp4');">Video1</button>
<div id="div_video"> </div>

回答by mkralla11

Yaur: Although what you have copied and pasted is good advice, this does not mean that it is impossible to change the source element of an HTML5 video element elegantly, even in IE9 (or IE8 for that matter).(This solution does NOT involve replacing the entire video element, as it is bad coding practice).

Yaur:虽然您复制粘贴的内容是很好的建议,但这并不意味着不可能优雅地更改 HTML5 视频元素的源元素,即使在 IE9(或 IE8)中也是如此。(此解决方案不涉及替换整个视频元素,因为这是不好的编码习惯)。

A complete solution to changing/switching videos in HTML5 video tags via javascript can be found hereand is tested in all HTML5 browser (Firefox, Chrome, Safari, IE9, etc).

可以在此处找到通过 javascript 更改/切换 HTML5 视频标签中的视频的完整解决方案,并在所有 HTML5 浏览器(Firefox、Chrome、Safari、IE9 等)中进行测试。

If this helps, or if you're having trouble, please let me know.

如果这有帮助,或者您遇到问题,请告诉我。

回答by molokoloco

I come with this to change video source dynamically. "canplay" event sometime doesn't fire in Firefox so i have added "loadedmetadata". Also i pause previous video if there is one...

我用这个来动态改变视频源。“canplay”事件有时不会在 Firefox 中触发,所以我添加了“loadedmetadata”。如果有的话,我也会暂停上一个视频...

var loadVideo = function(movieUrl) {
    console.log('loadVideo()');
    $videoLoading.show();
    var isReady = function (event) {
            console.log('video.isReady(event)', event.type);
            video.removeEventListener('canplay', isReady);
            video.removeEventListener('loadedmetadata', isReady);
            $videoLoading.hide();
            video.currentTime = 0;
            video.play();
        },
        whenPaused = function() {
            console.log('video.whenPaused()');
            video.removeEventListener('pause', whenPaused);
            video.addEventListener('canplay', isReady, false);
            video.addEventListener('loadedmetadata', isReady, false); // Sometimes Firefox don't trigger "canplay" event...
            video.src = movieUrl; // Change actual source
        };

    if (video.src && !video.paused) {
        video.addEventListener('pause', whenPaused, false);
        video.pause();
    }
    else whenPaused();
};

回答by IT Vlogs

This is my solution:

这是我的解决方案:

<video id="playVideo" width="680" height="400" controls="controls">
    <source id="sourceVideo" src="{{video.videoHigh}}" type="video/mp4">
</video>
    <br />
<button class="btn btn-warning" id="{{video.videoHigh}}" onclick="changeSource(this)">HD</button>
<button class="btn btn-warning" id="{{video.videoLow}}" onclick="changeSource(this)">Regular</button>

<script type="text/javascript">
    var getVideo = document.getElementById("playVideo");
    var getSource = document.getElementById("sourceVideo");
    function changeSource(vid) {
        var geturl = vid.id;
        getSource .setAttribute("src", geturl);
        getVideo .load()
        getVideo .play();
        getVideo .volume = 0.5;
    }
</script>