1
votes

I have a website with embedded YouTube videos. I'm using the YouTube player API to embed my videos, and the player is set to autoplay when the page loads. I've set a listen event to redirect to the next video once the current embedded video has finished playing (I need to redirect to a new physical page rather than load the next video into the existing iframe created by the API as each page contains information/comments specific to that video).

This all works perfectly, but only if you have the tab open. If you're listning to the videos in the background (they're just audio recordings set to a static image, there's nothing to actually watch), the page will redirect fine after the current video finishes, but the YouTube video will not start playing until you click into the tab. As soon as you do click into the tab, the autoplay kicks in and the video starts. But I need the videos to play automatically whether the tab is open or not. Any ideas?

I've experimented with JWplayer, and the redirect/autoplay works perfectly, but that would mean having to host the videos myself, and I'd rather host on YouTube. I've also noticed that YouTube.com doesn't have this problem. It will load the next video page in a playlist and autoplay whether the tab is open or not.

This problem only occurs in Chrome, Firefox and Opera, but not in Edge or IE.

Thanks.

<div id="yt-player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>

// create youtube player
var player;
function onYouTubePlayerAPIReady(){
    player = new YT.Player('yt-player',{
        height:'433',
        width:'770',
        videoId:'xxxxxxxxxxx',
        playerVars: { 'autoplay': 1, 'controls': 1, 'html5': 1 },
        events:{
            'onReady':onPlayerReady,
            'onStateChange':onPlayerStateChange
        }
    });
}

// autoplay video
function onPlayerReady(event){
    event.target.playVideo();
}

// when video ends
function onPlayerStateChange(event) {
    if(event.data === 0 && $("#autoplayCB").is(':checked')) {  
        window.location="/nextvideo.htm";
    }
}

</script>
1

1 Answers

0
votes

I've come across this problem. I found that you must create the player first, then to change the video you use loadVideoById.

https://developers.google.com/youtube/iframe_api_reference#Queueing_Functions

The problem here is that you must make the list of videos yourself, or find some way of getting the list of videos into a javascript array and call the next one when the current video ends. You will need to build a manual playlist.

The only other caveat is that you must let the video load the first time you're on the page, opening it in a new tab without giving the tab focus will prevent it from initialising until you do so.