Can I use javascript to dynamically change a video's source?
Asked Answered
S

10

37

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>
Suppurate answered 17/9, 2010 at 3:52 Comment(4)
What should be dynamic and what's the problem? Do you have any Javascript experience?Skelton
I want make a playlist, so after first video finished, play second video.Suppurate
I have js experience, I have done ended event like this $("#myVideo").bind('ended', function(){ // ??? How to play next });Suppurate
That snippet is jQuery. I've added a jQuery tag.Supernaturalism
S
37

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

Starlin answered 17/9, 2010 at 4:43 Comment(4)
Changing the src attribute of the source tag does nothing. Set it on the video tag directly.Symmetrize
i voted up, but this answer is actually wrong. there is no way to change the source tags: you need to change the src attribute in the video tag. this is the best solution i found so far: https://mcmap.net/q/127271/-changing-source-on-html5-video-tagLafond
Worked for me, just remember to call videoElement.load() for the changes to take effect.Meninges
"> source" give javascript error, How can remove thisNarwhal
A
21

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.

Analogize answered 25/8, 2015 at 22:54 Comment(0)
C
5

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.

Crowe answered 7/8, 2012 at 14:14 Comment(0)
C
2

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.

Cleo answered 24/1, 2017 at 11:40 Comment(1)
Thanks! Using the load() method worked for me after changing the src of the source tags with js. play() did not work.Facultative
S
1

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>
Salto answered 20/10, 2021 at 4:32 Comment(0)
N
0

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.

Nephoscope answered 24/9, 2012 at 21:0 Comment(1)
Why the downvote? The solution link provided in my answer is accurate and there is no reason to repost the entire solution from the other post here...if you are going to downvote, explain yourself.Nephoscope
T
0

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>
Trinia answered 30/10, 2016 at 14:16 Comment(0)
H
0

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();
    }); 
Hamulus answered 21/9, 2017 at 10:34 Comment(0)
M
0

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);
    }           
}
Myasthenia answered 27/6, 2019 at 16:6 Comment(0)
S
0

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

Samhita answered 19/8, 2020 at 17:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.