我可以使用 JavaScript 动态更改视频源吗?

发布于 2024-09-19 07:54:16 字数 258 浏览 4 评论 0 原文

如何使用 JS 更改视频来源?

<video id="myVideoTag" width="670" height="377" autoplay="true" controls="controls">
    <source src="http://www.test.com/test.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</video>

How can I change a video's source using JS?

<video id="myVideoTag" width="670" height="377" autoplay="true" controls="controls">
    <source src="http://www.test.com/test.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</video>

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

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

发布评论

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

评论(10

逆光飞翔i 2024-09-26 07:54:16

当然,

  1. 您可以在 source 元素上设置 src 属性:

    document.querySelector("#myVideoTag > source").src = "http://example.com/new_url.mp4"
    

    或者使用 jQuery 而不是标准 DOM 方法:

    $("#myVideoTag > source").attr("src", "http://example.com/new_url.mp4" ) 
    
  2. 然后您需要调用视频元素上的 load 方法:

    videoElement.load()

Sure,

  1. You can set the src attribute on the source element:

    document.querySelector("#myVideoTag > source").src = "http://example.com/new_url.mp4"
    

    Or using jQuery instead of standard DOM methods:

    $("#myVideoTag > source").attr("src", "http://example.com/new_url.mp4"​​​​)​
    
  2. Then you need to call the load method on the video element:

    videoElement.load()

善良天后 2024-09-26 07:54:16

我已经多次遇到这个问题,根据以前的经验和挖掘,我可以建议以下选项:

  • 完全替换视频标签

是的,只需重新插入 元素即可新来源。这是简单而有效的方法。不要忘记重新初始化事件侦听器。


  • 将视频 URL 分配给 video.src

这个我在 stackoverflow 上的答案以及 github 上的源代码中看到了很多。

var video = document.getElementById('#myVideo');
video.src = newSourceURL;

它可以工作,但您无法提供可供选择的浏览器选项。


  • 调用.load()视频元素

根据 。 asp" rel="noreferrer">文档 您可以更新 src 属性标签,然后调用 .load() 以使更改生效:

<video id="myVideo">
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogg" type="video/ogg" />
</video>

<script>
    var video = document.getElementById('myVideo');
    var sources = video.getElementsByTagName('source');
    sources[0].src = anotherMp4URL;
    sources[1].src = anotherOggURL;
    video.load();
</script>

尽管如此,这里据说有在某些浏览器中存在问题。

我希望将所有这些都集中在一个地方会很有用。

I have faced this problem several times and based on previous experience and digging I can suggest these options:

  • replace video tag completely

yes, just re-insert <video> element with new sources. It's straightforward, but effective approach. Don't forget to re-initialize event listeners.


  • assign video URL to video.src

this I saw a lot in answers here, on stackoverflow, and also in sources on github.

var video = document.getElementById('#myVideo');
video.src = newSourceURL;

It works, but you cannot provide browser options to choose from.


  • call .load() on video element

according to documentation you can update src attributes for <video>'s <source> tags and then call .load() to changes take effect:

<video id="myVideo">
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogg" type="video/ogg" />
</video>

<script>
    var video = document.getElementById('myVideo');
    var sources = video.getElementsByTagName('source');
    sources[0].src = anotherMp4URL;
    sources[1].src = anotherOggURL;
    video.load();
</script>

Nevertheless here it's said that there're problems in some browsers.

I hope it will be useful to have this all in one place.

善良天后 2024-09-26 07:54:16

我遇到了同样的问题。根据此线程:

更改 html5 视频标签上的源

这是不可能的更改源标签的 src。您必须使用视频标签本身的 src 。

I have run into the same problem. According to this thread:

changing source on html5 video tag

it is not possible to change the src of the source tag. you will have to use src of the video tag itself.

旧瑾黎汐 2024-09-26 07:54:16

这是有效的

<video id="videoplayer1" width="240" height="160" controls>
    <source id="video_res_1" src="" type="video/ogg">
</video>

,在 javascript 中

document.getElementById("video_res_1").src = "my video url.ogv";
document.getElementById("videoplayer1").load();

关键是重新加载视频播放器的 .load() 函数。

This is working

<video id="videoplayer1" width="240" height="160" controls>
    <source id="video_res_1" src="" type="video/ogg">
</video>

and in the javascript

document.getElementById("video_res_1").src = "my video url.ogv";
document.getElementById("videoplayer1").load();

The key is the .load() function that reloads the video player.

醉生梦死 2024-09-26 07:54:16

根据此规范说明。

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

You can modify the media src like so:

<audio src='./second-src'/>
    <source src='./first-src'/>
</audio>
不即不离 2024-09-26 07:54:16

尽管坎贝尔提供了正确的解决方案,但针对当前的“播放列表特定”问题(如评论中所述)提供了更完整的解决方案此处。如果正确实施,此解决方案可以应用于所有视频格式(我使用了 modernizr 来检测哪个源将播放给定的浏览器,结合上面的解决方案)。

该解决方案适用于(并且已经过测试)在所有 HTML5 浏览器(包括 IE8)中更改 HTML5 视频标签中的视频。

Although Campbell has provided the correct solution, a more complete solution to the 'playlist specific' question at hand (as noted in the comments) is provided here. This solution can be applied to all video formats if implemented correctly (I have used modernizr in order to detect which source will play for a given browser, combined with the solution above).

This solution will work (and has been tested) for changing videos in HTML5 video tags in ALL HTML5 browsers, including IE8.

椵侞 2024-09-26 07:54:16

看看这个。此 JavaScript 更改源标记的 src。
https://jsfiddle.net/a94zcrtq/8/

<script>
  function toggle() {
            if ($(this).attr('data-click-state') == 1) {
                $(this).attr('data-click-state', 0)
                document.getElementById("source").src = "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
                document.getElementById("videoPlayer").load();
            } else {
                $(this).attr('data-click-state', 1)
                document.getElementById("source").src = "http://techslides.com/demos/sample-videos/small.mp4";
                document.getElementById("videoPlayer").load();
            }
        } 
</script>

Check this out. This javascript changes the src of the source tag.
https://jsfiddle.net/a94zcrtq/8/

<script>
  function toggle() {
            if ($(this).attr('data-click-state') == 1) {
                $(this).attr('data-click-state', 0)
                document.getElementById("source").src = "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
                document.getElementById("videoPlayer").load();
            } else {
                $(this).attr('data-click-state', 1)
                document.getElementById("source").src = "http://techslides.com/demos/sample-videos/small.mp4";
                document.getElementById("videoPlayer").load();
            }
        } 
</script>

谜兔 2024-09-26 07:54:16

我希望它能工作,请根据您的需要调整属性名称和 ID

下面的 html 代码 下面的

<video controls style="max-width: 90%;" id="filePreview">                        
    <source type="video/mp4" id="video_source">
</video>

js 代码

   $("#fileToUpload").change(function(e){
        var source = $('#video_source');
        source[0].src = URL.createObjectURL(this.files[0]);
        source.parent()[0].load();
    }); 

i hope it should work and please adjust attribute name and id as per your need

html code below

<video controls style="max-width: 90%;" id="filePreview">                        
    <source type="video/mp4" id="video_source">
</video>

js code below

   $("#fileToUpload").change(function(e){
        var source = $('#video_source');
        source[0].src = URL.createObjectURL(this.files[0]);
        source.parent()[0].load();
    }); 
眼眸印温柔 2024-09-26 07:54:16

我发现动态创建和附加子 source 元素就可以解决问题。

var videoElement = document.querySelector('.my-video');
var videoSources = ["video.mp4","video.webm"]
if (videoElement) {
    for (var i = 0; i < videoSources.length; i++) {
        var sourceTag = document.createElement("source");
        sourceTag.type = "video/" + videoSources[i].split('.')[1];
        sourceTag.src = videoSources[i];
        videoElement.appendChild(sourceTag);
    }           
}

I found that dynamically creating and appending the child source elements did the trick.

var videoElement = document.querySelector('.my-video');
var videoSources = ["video.mp4","video.webm"]
if (videoElement) {
    for (var i = 0; i < videoSources.length; i++) {
        var sourceTag = document.createElement("source");
        sourceTag.type = "video/" + videoSources[i].split('.')[1];
        sourceTag.src = videoSources[i];
        videoElement.appendChild(sourceTag);
    }           
}
白馒头 2024-09-26 07:54:16

由于其他解决方案对我不起作用,这就是我所做的:

 <video width="400" controls id="the_id_of_your_video_here">
  <source src="path_to_first_video.mp4" type="video/mp4">
  Your browser does not support HTML video.
</video>

<button type="button" name="button" onclick="changeVid()">Click me to change the video</button>

<script>
function changeVid(){
  var video =  document.getElementById("the_id_of_your_video_here");
  video.src = 'path_to_second_video.mp4'; // Make sure to not use ..\ like in HTML but ../ if you have to give a more complex file path like: '../../myVideoFolder/myVideo.mp4'
  video.load();
}
</script>

不需要其他任何东西来让这个解决方案运行 - 除非我搞砸了......

Since the other solutions didn't work for me, here's what I did:

 <video width="400" controls id="the_id_of_your_video_here">
  <source src="path_to_first_video.mp4" type="video/mp4">
  Your browser does not support HTML video.
</video>

<button type="button" name="button" onclick="changeVid()">Click me to change the video</button>

<script>
function changeVid(){
  var video =  document.getElementById("the_id_of_your_video_here");
  video.src = 'path_to_second_video.mp4'; // Make sure to not use ..\ like in HTML but ../ if you have to give a more complex file path like: '../../myVideoFolder/myVideo.mp4'
  video.load();
}
</script>

Nothing else is needed to get this solution running - unless I messed up somehow...

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