I'm looking to change the video source of my VideoJS player dynamically. I tried one method of changing the source directly via the DOM and it did change it, but the player needs to reload. So looking at the official API here: http://docs.videojs.com/docs/api/player.html#Methodssrc
There's a method to change the source but when running the following code, it throws an error.
var source = dropdown.options[dropdown.selectedIndex].value;
var myVideo = videojs.getPlayers();
console.log(myVideo);
if (source == "Source2"){
myVideo.src([
{type: "application/x-mpegURL", src: "http://mycdn/playlist.m3u8"},
{type: "rtmp/mp4", src: "rtmp://mycdn"}
]);
}
Although the console does verify that myVideo is an object, calling the .src(source) function throws "TypeError: myVideo.src is not a function. (In 'myVideo.src', 'myVideo.src' is undefined)"
I've also found tutorials like this where the apparent more "official" way is to dispose of the player completely and reinitialize with new sources, but I can't seem to understand what he's doing. https://ineed.coffee/3201/how-to-dynamically-change-video-js-videos-and-captions-with-javascript/
Any help would be appreciated.
Solution: For testing purposes I just have a nice little drop down and added a click event to that, so it changes the channel to whatever the user wants.
var dropdown = document.getElementById('sel1');
var source = dropdown.options[dropdown.selectedIndex].value;
dropdown.addEventListener("click", function(){
source = dropdown.options[dropdown.selectedIndex].value;
console.log(source)
var myVideo = videojs('my-video');
console.log(myVideo);
if (source == "Public Access"){
myVideo.src([
{type: "application/x-mpegURL", src: "http://mycdns/playlist.m3u8"},
{type: "rtmp/mp4", src: "rtmp://mycdn"}
]);
}
else if (source == "Government"){
myVideo.src([
{type: "application/x-mpegURL", src: "http://mycdn/playlist.m3u8"},
{type: "rtmp/mp4", src: "rtmp://mycdn"}
]);
}
else if (source == "Regional"){
myVideo.src([
{type: "application/x-mpegURL", src: "http://mycdn/playlist.m3u8"},
{type: "rtmp/mp4", src: "rtmp://mysource"}
]);
}
});
getPlayers()
returns an object containing all players, not a player.
You'd normally get a particular player with videojs('my_player_id')
.