how to use method changeToMediaAtIndex tvmlkit js

301 Views Asked by At

how to use the method changeToMediaAtIndex in the tvmlkit js to change video in the playlist? When i use this method with the player class (player.changeToMediaAtIndex(2)) nothing happened...

1

There are 1 best solutions below

0
On BEST ANSWER

I was having issues with this too. My code looked like this.

var player = new Player();
player.playlist = new Playlist();
this.currentMediaItemIndex = 0;
for (var i = 0; i < videoItemsList.length; ++i) {

    var video = new MediaItem('video', videoItemsList[i].videoUrl.valueOf());

    video.artworkImageURL = videoItemsList[i].artworkUrl;
    video.title = videoItemsList[i].title;
    video.resumeTime = videoItemsList[i].watchedSeconds;
    if (videoItemList[i].videoId == this.startingVideoId) {
        this.currentMediaItemIndex = i;
    }
    player.playlist.push(video);
}

player.play();
player.changeToMediaAtIndex(this.currentMediaItemIndex);

I would call play and immediately call to change the media item. I tried different ordering (calling play after changing the item) and I noticed that when I stepped through the code, it would work as intended. Note that this.startingVideoId is set on the controller by an action before calling the play function that contains the above code. videoItemsList is also defined above and has Object's with the video information.

I decided to add an event listener and wait until I received an event from the player before trying to change the currentItem. I removed player.changeToMediaAtIndex(this.currentMediaItemIndex); from the play function and moved it into the event listener.

I added the event listener into the play function when the player is created like so.

    player.addEventListener("stateDidChange", this.stateDidChange);

Then I implemented the event listener to check the playlist and see if it is playing the right video when it goes into a playing state.

private stateDidChange = (event) => {
        if (event.state == "playing") {
            var player = <Player>event.target;
            for (var i = 0; i < player.playlist.length; ++i) {
                if (player.playlist.item(i) == player.currentMediaItem) {
                    if (i != this.currentMediaItemIndex) {
                        player.changeToMediaAtIndex(this.currentMediaItemIndex);
                    }
                    break; // break out of the loop since we don't care about the rest.
                }
            }
        }
    };

This works great now and always starts from the right location. You will need additional state tracking with event listeners, like changing the currentMediaItemIndex when the track changes, but this should get you on the right track I hope.

There still isn't a lot of good tvos answers on here yet. Hopefully this will help.

Happy programming.