Pass youtube iframe api events onstatechange when

2019-03-04 01:00发布

问题:

So I figured I would update this with a working example. I have ditched stating the iframe tag and just used the iframe api to create an iframe and then loaded the player by id with a data attribute. Here is a working example below. So now all statechanges are passed consistently through the youtube player. So the script will load an iframe into the Div #player and you can just loadVideoByID pretty easily with jquery and javascript.

<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        playerVars: { 'autoplay': 0,},
        videoId: 'M7lc1UVf-VE',
        events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
        }
    });
}
function onPlayerReady(event) {
    alert('started');
}
function onPlayerStateChange(event) {        
     if(event.data === 0) {            
         alert('done');
     }
}
$( document ).on( "click", ".video-link", function(e) {
    e.preventDefault();
    var videoID = $(this).attr('data-videoID');
    player.loadVideoById(videoID);
});
</script>

And then use a link with a data-attribute like so.

<a href="#" class="video-link"  data-videoID="youtube id here">Link</a>

回答1:

Rather than having buttons to play, why not cue to playlist when the player is ready? You can hold the video ID's in an array... If this isn't what you're looking for just leave a comment below and I will change things the best I can to fit.

//Array of videos
var MyVideos=["E6RGMRamAFk","IHQr0HCIN2w","CogIXrea6A4"];
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
    events: {
     'onReady': onPlayerReady,
     'onStateChange': onPlayerStateChange
    }
  });
}
function onPlayerReady(event) {
//Player is ready, cue the array of videos into the playlist.
player.cuePlaylist(MyVideos);
}
function onPlayerStateChange(event) {
}

JS Fiddle - Working Demo

YouTube JavaScript Player API Reference

If you have any questions please leave a comment below and I will get back to you as soon as possible.

I hope this help. Happy coding!