YouTube API - onPlayerStateChange

喜你入骨 提交于 2019-12-31 01:48:25

问题


I'm using the YouTube API in conjunction with Cyclone Slider. The goal is to pause the slideshow once the YouTube starts playing. I'm using the following code which works nicely:

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

<script>
var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('video', {
      events: {
        'onStateChange': onPlayerStateChange
      }
    });
}

function onPlayerStateChange(event) {
    if(event.data === 1) {
        $(".cycle-slideshow").cycle('pause');
    }

    if(event.data === 2) {
        $(".cycle-slideshow").cycle('resume');
    }
}
</script>

However, it only seems to work if I do a refresh of the page. If I navigate between pages and return to the homepage, it will no longer work.

Any suggestions for why this is the case? I've tried a few suggestions I found on Google but couldn't get any to work. I'm a little lost on this one.

Any help would be greatly appreciated.


回答1:


Try the following code, it works for me -

function loadYouTube(targetId){
    ytplayer = new YT.Player(targetId, {
        events: {
            'onStateChange': function(event){
                /** YouTube API
                        -1 (unstarted)
                        0 (ended)
                        1 (playing)
                        2 (paused)
                        3 (buffering)
                        5 (video cued)
                 **/
                if (event.data == 1) {
//do your work here
                }
                console.log(event.data)
            }
        }    
    });
}


来源:https://stackoverflow.com/questions/29553570/youtube-api-onplayerstatechange

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