HunchoDevelo
HunchoDevelo

Reputation: 17

Video.js changing source, but does not show new source

Sorry for my lack of knowledge on this topic

I have a script that changes the source of the video player. And it does just that. The only problem is that the Video.js player plays the first source assigned to it.

document.getElementById("vid-player_html5_api").innerHTML = "";

document.getElementById("vid-player_html5_api").innerHTML = "<source src='" + link + "' type='video/mp4'>";
document.getElementById("vid-player_html5_api").muted = false;

So if there were two buttons, and you clicked Button 1 it would change the source of the player and show the correct video. Then lets say you clicked Button 2 it would change the source of the player, but it would still show the same video it showed for Button 1

It is proven that it changes the source, I checked the Chrome Dev tools and surely enough it changed the source

How do I fix this?

Upvotes: 1

Views: 20260

Answers (5)

Usama Maqsood
Usama Maqsood

Reputation: 76

For React Dont return this in useEffect

 return() => {
        if(player){
            player.dispose()
        }
    }

Upvotes: 0

MSaudi
MSaudi

Reputation: 4652

The only way that worked with me is like that

var player = videojs(document.querySelector('.video-js'));
  player.src({
                src: 'videoURL,
                type: 'video/mp4'/*video type*/
            });

  player.play();

Upvotes: 5

ajayel
ajayel

Reputation: 3085

Just found this post the current pattern in VideoJS is to set .src with a JSON object for example

player.src({ type: 'video/mp4', src: new_url });

Upvotes: 14

Aruna
Aruna

Reputation: 12022

You can try as below,

function playVideo(videoSource, type) {
  var videoElm = document.getElementById('testVideo');
  var videoSourceElm = document.getElementById('testVideoSource'); 
   if (!videoElm.paused) {
        videoElm.pause();
     }
    
   videoSourceElm.src = videoSource;
   videoSourceElm.type = type;
  
    videoElm.load();
    videoElm.play();
  }
<video id="testVideo" width="400" controls>
  <source id="testVideoSource">
</video>
<br/>
<input type="button" value="Play Video 1" onclick="playVideo('http://www.w3schools.com/html/mov_bbb.mp4', 'video/mp4')" />
<input type="button" value="Play Video 2" onclick="playVideo('http://www.w3schools.com/html/mov_bbb.ogg', 'video/ogg')" />

Upvotes: 6

AM Douglas
AM Douglas

Reputation: 1903

You need to call video.js again once you've loaded the new video:

var current_vid = document.getElementById("vid-player_html5_api")
var next_vid = document.createElement('video');

next_vid.innerHTML = '<source src="' + link + '" type="video/mp4">';
next_vid.muted = false;

current_vid.parentNode.replaceChild( next_vid, current_vid );

videojs(current_vid, {}, function(){
  // do something when video.js is ready
});

Video.js: dynamically loaded videos

Upvotes: 0

Related Questions