更改 html5 视频标签的源

发布于 2024-10-20 18:35:01 字数 1849 浏览 2 评论 0原文

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

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

如在多个网站上看到的,例如适合所有人的视频) 到目前为止,一切都很好。

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

所以我的 JS 更改 标签应该是这样的:

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

问题是,这并不适用于所有浏览器。也就是说,在 Firefox 中有一个很好的页面,您可以在其中观察我遇到的问题: http://www.w3.org/2010/05/video/mediaevents.html

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

现在我发现,当我不使用多个 标记时,而是在 中仅使用一个 src 属性code> 标签,整个事情在 Firefox 中都可以工作。

所以我的计划是只使用 src 属性并使用 canPlayType() 函数。

我是不是做错了什么或者让事情变得复杂了?

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 Flash player (and thus IE) part for the time being, I will try to deal with that later.

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

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

The problem is, this doesn't work in all browsers. Namely, in Firefox there is a nice page where you can observe the problem I'm having: 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.

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.

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

Am I doing it wrong somehow or complicating things?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

自找没趣 2024-10-27 18:35:01

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

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

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

source.setAttribute('src', 'http://techslides.com/demos/sample-videos/small.mp4');
source.setAttribute('type', 'video/mp4');

video.appendChild(source);
video.play();
console.log({
  src: source.getAttribute('src'),
  type: source.getAttribute('type'),
});

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

  source.setAttribute('src', 'http://techslides.com/demos/sample-videos/small.webm');
  source.setAttribute('type', 'video/webm');

  video.load();
  video.play();
  console.log({
    src: source.getAttribute('src'),
    type: source.getAttribute('type'),
  });
}, 3000);
<video id="video" width="320" height="240"></video>

外部链接

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:

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

source.setAttribute('src', 'http://techslides.com/demos/sample-videos/small.mp4');
source.setAttribute('type', 'video/mp4');

video.appendChild(source);
video.play();
console.log({
  src: source.getAttribute('src'),
  type: source.getAttribute('type'),
});

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

  source.setAttribute('src', 'http://techslides.com/demos/sample-videos/small.webm');
  source.setAttribute('type', 'video/webm');

  video.load();
  video.play();
  console.log({
    src: source.getAttribute('src'),
    type: source.getAttribute('type'),
  });
}, 3000);
<video id="video" width="320" height="240"></video>

External Link

人事已非 2024-10-27 18:35:01

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

我所做的是我没有使用。不知怎的,这把事情搞砸了,因为视频只在第一次调用 load() 时才工作。相反,我在视频标签内使用了 source 属性 -> 并使用 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>

希望这会对您有所帮助:)

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

Modernizr worked like a charm for me.

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 Modernizr to determine what format the browser supported.

<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().

赠意 2024-10-27 18:35:01

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

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

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

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:

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.

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

余罪 2024-10-27 18:35:01

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

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

I solved this with this simple method

function changeSource(url) {
   var video = document.getElementById('video');
   video.src = url;
   video.play();
}
贱贱哒 2024-10-27 18:35:01

为什么不删除整个 元素并重新创建它,而不是使用相同的视频播放器加载新文件。如果 src 正确,大多数浏览器会自动加载它。

示例(使用 原型):

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

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.

Example (using 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);
永不分离 2024-10-27 18:35:01

根据规范

动态修改源元素及其属性
元素已插入视频或音频元素将不会
影响。要更改正在播放的内容,只需使用 src 属性
直接媒体元素,可能使用 canPlayType()
从可用资源中进行选择的方法。一般来说,
文档生成后手动操作源元素
parsed 是一种不必要的复杂方法。

所以你想做的事情显然不应该起作用。

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.

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

海未深 2024-10-27 18:35:01

只需放置一个 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>

Just put a div and update the content...

<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>
℡寂寞咖啡 2024-10-27 18:35:01

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

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

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

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).

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

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

千纸鹤 2024-10-27 18:35:01

这是我的解决方案:

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

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>
抹茶夏天i‖ 2024-10-27 18:35:01

我有一个类似的网络应用程序,但根本没有遇到此类问题。我所做的是这样的:

var sources = new Array();

sources[0] = /path/to/file.mp4
sources[1] = /path/to/another/file.ogg
etc..

然后,当我想更改源时,我有一个执行类似操作的函数:

this.loadTrack = function(track){
var mediaSource = document.getElementsByTagName('source')[0];
mediaSource.src = sources[track];

    var player = document.getElementsByTagName('video')[0];
    player.load();

}

我这样做是为了让用户可以通过播放列表,但您可以检查 userAgent 然后加载这样就可以找到适当的文件。我尝试像互联网上每个人建议的那样使用多个源标签,但我发现操作单个源标签的 src 属性更干净、更可靠。上面的代码是凭记忆编写的,因此我可能掩盖了一些细节,但总体思路是在适当的时候使用 JavaScript 动态更改源标记的 src 属性。

I have a similar web app and am not facing that sort of problem at all. What i do is something like this:

var sources = new Array();

sources[0] = /path/to/file.mp4
sources[1] = /path/to/another/file.ogg
etc..

then when i want to change the sources i have a function that does something like this:

this.loadTrack = function(track){
var mediaSource = document.getElementsByTagName('source')[0];
mediaSource.src = sources[track];

    var player = document.getElementsByTagName('video')[0];
    player.load();

}

I do this so that the user can make their way through a playlist, but you could check for userAgent and then load the appropriate file that way. I tried using multiple source tags like everyone on the internet suggested, but i found it much cleaner, and much more reliable to manipulate the src attribute of a single source tag. The code above was written from memory, so i may have glossed over some of hte details, but the general idea is to dynamically change the src attribute of the source tag using javascript, when appropriate.

南…巷孤猫 2024-10-27 18:35:01

您可以在 Jquery 中执行另一种方法。

HTML

<video id="videoclip" controls="controls" poster="" title="Video title">
    <source id="mp4video" src="video/bigbunny.mp4" type="video/mp4"  />
</video>

<div class="list-item">
     <ul>
         <li class="item" data-video = "video/bigbunny.mp4"><a href="javascript:void(0)">Big Bunny.</a></li>
     </ul>
</div>

查询

$(".list-item").find(".item").on("click", function() {
        let videoData = $(this).data("video");
        let videoSource = $("#videoclip").find("#mp4video");
        videoSource.attr("src", videoData);
        let autoplayVideo = $("#videoclip").get(0);
        autoplayVideo.load();
        autoplayVideo.play();
    });

Another way you can do in Jquery.

HTML

<video id="videoclip" controls="controls" poster="" title="Video title">
    <source id="mp4video" src="video/bigbunny.mp4" type="video/mp4"  />
</video>

<div class="list-item">
     <ul>
         <li class="item" data-video = "video/bigbunny.mp4"><a href="javascript:void(0)">Big Bunny.</a></li>
     </ul>
</div>

Jquery

$(".list-item").find(".item").on("click", function() {
        let videoData = $(this).data("video");
        let videoSource = $("#videoclip").find("#mp4video");
        videoSource.attr("src", videoData);
        let autoplayVideo = $("#videoclip").get(0);
        autoplayVideo.load();
        autoplayVideo.play();
    });
森林很绿却致人迷途 2024-10-27 18:35:01

我用这个来动态改变视频源。 “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();
};

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...

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();
};
望她远 2024-10-27 18:35:01

事实证明,在 Chrome 14.0.835.202 中使用 标签对我来说很困难,尽管它在 FireFox 中工作得很好。 (这可能是我缺乏知识,但我认为替代解决方案可能有用。)因此,我最终只使用

顺便说一下,FireFox 和 Chrome 都播放“ogg”格式,尽管 Chrome 推荐“webm”。我首先检查浏览器对“ogg”的支持,只是因为其他帖子提到 FireFox 更喜欢 ogg 源(即 )。但是,我还没有测试(并且高度怀疑)在视频标签上设置“src”时,代码中的顺序是否有任何区别。

HTML

<body onload="setupVideo();">
    <video id="media" controls="true" preload="auto" src="">
    </video>
</body>

JavaScript

function setupVideo() {
       // You will probably get your video name differently
       var videoName = "http://video-js.zencoder.com/oceans-clip.mp4";

       // Get all of the uri's we support
       var indexOfExtension = videoName.lastIndexOf(".");
       //window.alert("found index of extension " + indexOfExtension);
       var extension = videoName.substr(indexOfExtension, videoName.length - indexOfExtension);
       //window.alert("extension is " + extension);
       var ogguri = encodeURI(videoName.replace(extension, ".ogv"));
       var webmuri = encodeURI(videoName.replace(extension, ".webm"));
       var mp4uri = encodeURI(videoName.replace(extension, ".mp4"));
       //window.alert(" URI is " + webmuri);


       // Get the video element
       var v = document.getElementById("media");
       window.alert(" media is " + v);

       // Test for support
       if (v.canPlayType("video/ogg")) {
            v.setAttribute("src", ogguri);
           //window.alert("can play ogg");
       }
       else if (v.canPlayType("video/webm")) {
           v.setAttribute("src", webmuri);
           //window.alert("can play webm");
       }
       else if (v.canPlayType("video/mp4")) {
           v.setAttribute("src", mp4uri);
           //window.alert("can play mp4");
       }
       else {
           window.alert("Can't play anything");
       }

      v.load();
      v.play();
  }

Using the <source /> tags proved difficult for me in Chrome 14.0.835.202 specifically, although it worked fine for me in FireFox. (This could be my lack of knowledge, but I thought an alternate solution might be useful anyway.) So, I ended up just using a <video /> tag and setting the src attribute right on the video tag itself. The canPlayVideo('<mime type>') function was used to determine whether or not the specific browser could play the input video. The following works in FireFox and Chrome.

Incidently, both FireFox and Chrome are playing the "ogg" format, although Chrome recommends "webm". I put the check for browser support of "ogg" first only because other posts have mentioned that FireFox prefers the ogg source first (i.e. <source src="..." type="video/ogg"/> ). But, I haven't tested (and highly doubt) whether or not it the order in the code makes any difference at all when setting the "src" on the video tag.

HTML

<body onload="setupVideo();">
    <video id="media" controls="true" preload="auto" src="">
    </video>
</body>

JavaScript

function setupVideo() {
       // You will probably get your video name differently
       var videoName = "http://video-js.zencoder.com/oceans-clip.mp4";

       // Get all of the uri's we support
       var indexOfExtension = videoName.lastIndexOf(".");
       //window.alert("found index of extension " + indexOfExtension);
       var extension = videoName.substr(indexOfExtension, videoName.length - indexOfExtension);
       //window.alert("extension is " + extension);
       var ogguri = encodeURI(videoName.replace(extension, ".ogv"));
       var webmuri = encodeURI(videoName.replace(extension, ".webm"));
       var mp4uri = encodeURI(videoName.replace(extension, ".mp4"));
       //window.alert(" URI is " + webmuri);


       // Get the video element
       var v = document.getElementById("media");
       window.alert(" media is " + v);

       // Test for support
       if (v.canPlayType("video/ogg")) {
            v.setAttribute("src", ogguri);
           //window.alert("can play ogg");
       }
       else if (v.canPlayType("video/webm")) {
           v.setAttribute("src", webmuri);
           //window.alert("can play webm");
       }
       else if (v.canPlayType("video/mp4")) {
           v.setAttribute("src", mp4uri);
           //window.alert("can play mp4");
       }
       else {
           window.alert("Can't play anything");
       }

      v.load();
      v.play();
  }
暮色兮凉城 2024-10-27 18:35:01

我已经研究这个问题很长一段时间了,我正在尝试做同样的事情,所以希望这对其他人有帮助。我一直在使用 crossbrowsertesting.com 并在几乎所有人类已知的浏览器中进行测试。我得到的解决方案目前适用于 Opera、Chrome、Firefox 3.5+、IE8+、iPhone 3GS、iPhone 4、iPhone 4s、iPhone 5、iPhone 5s、iPad 1+、Android 2.3+、Windows Phone 8。

动态更改源

动态更改视频非常困难,如果您想要 Flash 后备,则必须从 DOM/页面中删除视频并重新添加它,以便 Flash 更新,因为 Flash 无法识别动态更新到 Flash 变量。如果您要使用 JavaScript 动态更改它,我将完全删除所有 元素,只使用 canPlayType 在 JavaScript 中设置 srcbreak< /code> 或 return 在第一个支持的视频类型之后,不要忘记动态更新 flash var mp4。此外,除非您调用 video.load(),否则某些浏览器不会注册您更改了源。我相信您遇到的 .load() 问题可以通过首先调用 video.pause() 来解决。删除和添加视频元素可能会减慢浏览器的速度,因为它会继续缓冲已删除的视频,但是有一个解决方法

跨浏览器支持

就实际的跨浏览器部分而言,我到达了Video For Every 也是如此。我已经尝试过 MediaelementJS Wordpress 插件,结果导致的问题比它解决的问题多得多。我怀疑问题是由 Wordpress 插件造成的,而不是实际的库造成的。如果可能的话,我正在尝试寻找无需 JavaScript 即可工作的东西。到目前为止,我想出的是这个简单的 HTML:

<video width="300" height="150" controls="controls" poster="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" class="responsive">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm" />
<source src="http://alex-watson.net/wp-content/uploads/2014/07/big_buck_bunny.iphone.mp4" type="video/mp4" />
<source src="http://alex-watson.net/wp-content/uploads/2014/07/big_buck_bunny.iphone3g.mp4" type="video/mp4" />
<object type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" width="561" height="297">
    <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
    <param name="allowFullScreen" value="true" />
    <param name="wmode" value="transparent" />
    <param name="flashVars" value="config={'playlist':['http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg',{'url':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4','autoPlay':false}]}" />
    <img alt="No Video" src="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" width="561" height="297" title="No video playback capabilities, please download the video below" />
</object>
<strong>Download video:</strong>  <a href="video.mp4">MP4 format</a> | <a href="video.ogv">Ogg format</a> | <a href="video.webm">WebM format</a>
</video>

重要说明

  • 最终将 ogg 作为第一个 因为 Mac OS Firefox 停止尝试如果遇到 MP4 作为第一个 则播放视频。
  • 正确的 MIME 类型很重要 .ogv 文件应该是 video/ogg不是 video/ogv
  • 如果您有高清视频,我发现的高清质量 OGG 文件的最佳转码器是 Firefogg
  • .iphone.mp4 文件适用于 iPhone 4+,它播放带有 H.264 Baseline 3 视频和 AAC 音频的 MPEG-4 视频。我发现该格式的最佳转码器是 Handbrake,使用 iPhone 和 Android 设备。 iPod Touch 预设可在 iPhone 4+ 上使用,但要让 iPhone 3GS 工作,您需要使用分辨率低得多的 iPod 预设,我将其添加为 video.iphone3g .mp4。
  • 将来,我们将能够在 元素上使用 media 属性来通过媒体查询定位移动设备,但目前较旧的 Apple 和 Android 设备支持得不够好。

编辑

  • 我仍在使用 Video For Every,但现在我已过渡到使用 FlowPlayer 来控制 Flash 后备,它具有很棒的 JavaScript API 可用于控制它。

I have been researching this for quite a while and I am trying to do the same thing, so hopefully this will help someone else. I have been using crossbrowsertesting.com and literally testing this in almost every browser known to man. The solution I've got currently works in Opera, Chrome, Firefox 3.5+, IE8+, iPhone 3GS, iPhone 4, iPhone 4s, iPhone 5, iPhone 5s, iPad 1+, Android 2.3+, Windows Phone 8.

Dynamically Changing Sources

Dynamically changing the video is very difficult, and if you want a Flash fallback you will have to remove the video from the DOM/page and re-add it so that Flash will update because Flash will not recognize dynamic updates to Flash vars. If you're going to use JavaScript to change it dynamically, I would completely remove all <source> elements and just use canPlayType to set the src in JavaScript and break or return after the first supported video type and don't forget to dynamically update the flash var mp4. Also, some browsers won't register that you changed the source unless you call video.load(). I believe the issue with .load() you were experiencing can be fixed by first calling video.pause(). Removing and adding video elements can slow down the browser because it continues buffering the removed video, but there's a workaround.

Cross-browser Support

As far as the actual cross-browser portion, I arrived at Video For Everybody as well. I already tried the MediaelementJS Wordpress plugin, which turned out to cause a lot more issues than it resolved. I suspect the issues were due to the Wordpress plug-in and not the actually library. I'm trying to find something that works without JavaScript, if possible. So far, what I've come up with is this plain HTML:

<video width="300" height="150" controls="controls" poster="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" class="responsive">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm" />
<source src="http://alex-watson.net/wp-content/uploads/2014/07/big_buck_bunny.iphone.mp4" type="video/mp4" />
<source src="http://alex-watson.net/wp-content/uploads/2014/07/big_buck_bunny.iphone3g.mp4" type="video/mp4" />
<object type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" width="561" height="297">
    <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
    <param name="allowFullScreen" value="true" />
    <param name="wmode" value="transparent" />
    <param name="flashVars" value="config={'playlist':['http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg',{'url':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4','autoPlay':false}]}" />
    <img alt="No Video" src="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" width="561" height="297" title="No video playback capabilities, please download the video below" />
</object>
<strong>Download video:</strong>  <a href="video.mp4">MP4 format</a> | <a href="video.ogv">Ogg format</a> | <a href="video.webm">WebM format</a>
</video>

Important notes:

  • Ended up putting the ogg as the first <source> because Mac OS Firefox quits trying to play the video if it encounters an MP4 as the first <source>.
  • The correct MIME types are important .ogv files should be video/ogg, not video/ogv
  • If you have HD video, the best transcoder I've found for HD quality OGG files is Firefogg
  • The .iphone.mp4 file is for iPhone 4+ which will only play videos that are MPEG-4 with H.264 Baseline 3 Video and AAC audio. The best transcoder I found for that format is Handbrake, using the iPhone & iPod Touch preset will work on iPhone 4+, but to get iPhone 3GS to work you need to use the iPod preset which has much lower resolution which I added as video.iphone3g.mp4.
  • In the future we will be able to use a media attribute on the <source> elements to target mobile devices with media queries, but right now the older Apple and Android devices don't support it well enough.

Edit:

  • I'm still using Video For Everybody but now I've transitioned to using FlowPlayer, to control the Flash fallback, which has an awesome JavaScript API that can be used to control it.
林空鹿饮溪 2024-10-27 18:35:01

实际上在html中更改视频非常简单,只需 .load() 方法就足够了我在Google上测试了它并创建了一个简单的视频更改页面来测试它,请看我的代码,这里我使用了一个API给我随机视频网址,但有时它会给我 jpg 或其他格式,这就是为什么我需要尝试 if else 语句

    async function FetchDog() {
        let response = await fetch("https://random.dog/woof.json");
        let data = await response.json();
        let url = data.url;
        let extension = url.slice(url.length-3,url.length);
        if(extension === 'mp4'){
          document.getElementById("dogVideo").setAttribute("src", url);
          document.getElementById("video").load();
        }
         console.log(url);
      }
<!DOCTYPE html>
<html>
  <body>
    <video id="video" width="320" height="240" controls>
      <source
        id="dogVideo"
        src="https://random.dog/5ab72e24-0ae5-45d4-aaaa-10e4bfc021b6.mp4"
        type="video/mp4"
      />
      Your browser does not support the video tag.
    </video>
    <br />
    <br />
    <p id="response"></p>
    <button onclick="FetchDog()">Fetch dog video</button>
   <sript src='your_js_file'> </script>
  </body>
</html>

Actually changing video in html is very simple just .load() method is enough I tested it on Google and created a simple video changing page to test it out, please look at my code, here I used an API to give me random video url but sometimes it gives me jpg or another format that`s why I needed to try if else statement

    async function FetchDog() {
        let response = await fetch("https://random.dog/woof.json");
        let data = await response.json();
        let url = data.url;
        let extension = url.slice(url.length-3,url.length);
        if(extension === 'mp4'){
          document.getElementById("dogVideo").setAttribute("src", url);
          document.getElementById("video").load();
        }
         console.log(url);
      }
<!DOCTYPE html>
<html>
  <body>
    <video id="video" width="320" height="240" controls>
      <source
        id="dogVideo"
        src="https://random.dog/5ab72e24-0ae5-45d4-aaaa-10e4bfc021b6.mp4"
        type="video/mp4"
      />
      Your browser does not support the video tag.
    </video>
    <br />
    <br />
    <p id="response"></p>
    <button onclick="FetchDog()">Fetch dog video</button>
   <sript src='your_js_file'> </script>
  </body>
</html>

禾厶谷欠 2024-10-27 18:35:01

更改视频源的最干净的解决方案:

    <video id="video" autoplay loop muted>
        <source id="source" src="video/default.mp4" type="video/mp4" />
    </video>

    function changeVideo(name) {
        const video = document.getElementById('video');
        const source = document.getElementById('source');
    
        source.setAttribute('src', `video/${name}.mp4`);
        video.load()
    }

    changeVideo('newVideoName')

The cleanest solution to change the source of the video:

    <video id="video" autoplay loop muted>
        <source id="source" src="video/default.mp4" type="video/mp4" />
    </video>

    function changeVideo(name) {
        const video = document.getElementById('video');
        const source = document.getElementById('source');
    
        source.setAttribute('src', `video/${name}.mp4`);
        video.load()
    }

    changeVideo('newVideoName')

夜深人未静 2024-10-27 18:35:01

尝试将 OGG 源移至顶部。我注意到,当 Firefox 想要播放的 OGG 不是第一个时,它有时会感到困惑并停止播放器。

值得一试。

Try moving the OGG source to the top. I've noticed Firefox sometimes gets confused and stops the player when the one it wants to play, OGG, isn't first.

Worth a try.

路弥 2024-10-27 18:35:01

根据规范说明。

当元素被修改时动态修改源元素及其属性
已插入视频或音频元素的将不会产生任何效果。到
更改正在播放的内容,只需使用媒体上的 src 属性
直接元素

所以假设你有:

<audio>
    <source src='./first-src'/>
</audio>

修改 src:

<audio src='./second-src'/>
    <source src='./first-src'/>
</audio>

You shouldn't try to change the src attribute of a source element, according to this spec note .

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

So lets say you have:

<audio>
    <source src='./first-src'/>
</audio>

To modify the src:

<audio src='./second-src'/>
    <source src='./first-src'/>
</audio>
青朷 2024-10-27 18:35:01

如果您已经加载了一个视频,并且尝试在该视频上上传新视频,请确保在第二个视频上使用 videoRef.load(),否则它将无法加载。

*videoRef 应该是显示的的引用标签

if you already have a loaded video and you try to upload a new one over that one make sure to use the videoRef.load() on the second one, otherwise it wont load.

*videoRef should be the ref of the displayed <video></video> tag

疯了 2024-10-27 18:35:01

如果有人仍在寻找这个解决方案,那么这是 2024 年的普通 JS 解决方案。
我在手机上测试过并且可以工作。

const player = document.getElementById("player");

playVideo("https://www.w3schools.com/html/mov_bbb.mp4");

/**
 * Play a video source to the video player.
 * type {String} src video source.
 */
function playVideo(src)
{
  const source = player.querySelector("source");
  source.src = src;
  source.type = "video/mp4";
  player.load();
  player.play();
}
<video id="player" width="400px" controls >
  <source type="video/mp4" >
  Your browser does not support HTML5 video.
</video>

This is a vanilla JS solution in 2024 if anyone still looking for this.
I tested it on mobile and works.

const player = document.getElementById("player");

playVideo("https://www.w3schools.com/html/mov_bbb.mp4");

/**
 * Play a video source to the video player.
 * type {String} src video source.
 */
function playVideo(src)
{
  const source = player.querySelector("source");
  source.src = src;
  source.type = "video/mp4";
  player.load();
  player.play();
}
<video id="player" width="400px" controls >
  <source type="video/mp4" >
  Your browser does not support HTML5 video.
</video>

玩世 2024-10-27 18:35:01

使用 JavaScript 和 jQuery:

<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
    $("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>

Using JavaScript and jQuery:

<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
    $("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>
逆夏时光 2024-10-27 18:35:01

我最终将接受的答案变成了一个函数,并改进了简历以保持时间。总长DR

    /**
     * https://stackoverflow.com/a/18454389/4530300
     * This inspired a little function to replace a video source and play the video.
     * @param video
     * @param source
     * @param src
     * @param type
     */
    function swapSource(video, source, src, type) {
        let dur = video.duration;
        let t = video.currentTime;
        // var video = document.getElementById('video');
        // var source = document.createElement('source');
        video.pause();
        source.setAttribute('src', src);
        source.setAttribute('type', type);

        video.load();
        video.currentTime = t;
        // video.appendChild(source);
        video.play();
        console.log("Updated Sorce: ", {
            src: source.getAttribute('src'),
            type: source.getAttribute('type'),
        });
    }

I ended up making the accepted ansower into a function and improving the resume to keep the time. TLDR

    /**
     * https://stackoverflow.com/a/18454389/4530300
     * This inspired a little function to replace a video source and play the video.
     * @param video
     * @param source
     * @param src
     * @param type
     */
    function swapSource(video, source, src, type) {
        let dur = video.duration;
        let t = video.currentTime;
        // var video = document.getElementById('video');
        // var source = document.createElement('source');
        video.pause();
        source.setAttribute('src', src);
        source.setAttribute('type', type);

        video.load();
        video.currentTime = t;
        // video.appendChild(source);
        video.play();
        console.log("Updated Sorce: ", {
            src: source.getAttribute('src'),
            type: source.getAttribute('type'),
        });
    }

扛刀软妹 2024-10-27 18:35:01

视频存储在网站本地目录中,并使用完整访问
URL,不想转换为blob对象并访问。

视频 HTML5 标签

 <video id="videoHelp" width="560" height="340" controls autoplay 
    muted>
    <source id="videoHelpSRC" src="" type='video/mp4'>
    </video>

点击锚标记时更改视频源

<a onclick="changeSource('Video-1.mp4'); return false;" 
href="">Video-1</a>
<a onclick="changeSource('Video-2.mp4'); return false;" 
href="">Video-2</a>

单击锚标记时更改视频源的 Java 脚本

function changeSource(videoName) {
        var videoPlayer = document.getElementById('videoHelp');

        /*Remove child - only need one video source at a time */
        while (videoPlayer.firstChild) {
            videoPlayer.firstChild.remove()
        }
        videoPlayer.load();

        var source = document.createElement('source');
        source.setAttribute('src', window.location.origin + 
'/Content/Videos/' + videoName);
        source.setAttribute('type', 'video/mp4');
        videoPlayer.appendChild(source);
        videoPlayer.play();
    }

Videos are stored in website local directory and accessed using full
URL, do not want to convert to blob object and access.

Video HTML5 tag

 <video id="videoHelp" width="560" height="340" controls autoplay 
    muted>
    <source id="videoHelpSRC" src="" type='video/mp4'>
    </video>

Change Video Source when anchor tags clicked

<a onclick="changeSource('Video-1.mp4'); return false;" 
href="">Video-1</a>
<a onclick="changeSource('Video-2.mp4'); return false;" 
href="">Video-2</a>

Java script which change video source when anchor tag clicked

function changeSource(videoName) {
        var videoPlayer = document.getElementById('videoHelp');

        /*Remove child - only need one video source at a time */
        while (videoPlayer.firstChild) {
            videoPlayer.firstChild.remove()
        }
        videoPlayer.load();

        var source = document.createElement('source');
        source.setAttribute('src', window.location.origin + 
'/Content/Videos/' + videoName);
        source.setAttribute('type', 'video/mp4');
        videoPlayer.appendChild(source);
        videoPlayer.play();
    }

与他有关 2024-10-27 18:35:01

女巫对我来说最简单的工作方式:

Html 代码:

<video width="100%" id="headerVideo" loop>
       <source src="videos/illustration.mp4" type="video/mp4">
</video>

Js 代码:

function loadDifferentVideo(src){
    headerVideo.getElementsByTagName('source')[0].setAttribute('src',src);
    headerVideo.load();
    headerVideo.play();
}

loadDifferentVideo('videos/illustration.mp4');

Simplest way witch is worked for me:

Html Code:

<video width="100%" id="headerVideo" loop>
       <source src="videos/illustration.mp4" type="video/mp4">
</video>

Js code:

function loadDifferentVideo(src){
    headerVideo.getElementsByTagName('source')[0].setAttribute('src',src);
    headerVideo.load();
    headerVideo.play();
}

loadDifferentVideo('videos/illustration.mp4');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文