Pass youtube iframe api events onstatechange when src changes

核能气质少年 提交于 2019-12-02 15:01:26

问题


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!



来源:https://stackoverflow.com/questions/32001845/pass-youtube-iframe-api-events-onstatechange-when-src-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!