YouTube OnStateChange with multiple players on the same page

时间:2016-07-11 22:01:08

标签: api youtube

I have multiple YouTube players on a single page inside a banner slider and I want to use the YouTube Player API to control them and do other stuff based on the state of the video's. I have the code below which I'm pretty sure of used to work fine where any state changes where registered. But it doesnt work for me anymore. The YouTube object is still there and I can use it to start and stop a video but the onStateChange event never gets triggered. What is wrong with this code?

var YT_ready = (function() {
    var onReady_funcs = [],
    api_isReady = false;
    return function(func, b_before) {
        if (func === true) {
            api_isReady = true;
            for (var i = 0; i < onReady_funcs.length; i++) {
                onReady_funcs.shift()();
            }
        }
        else if (typeof func == "function") {
            if (api_isReady) func();
            else onReady_funcs[b_before ? "unshift" : "push"](func);
        }
    }
})();
function onYouTubePlayerAPIReady() {
    YT_ready(true);
}

var players_homepage = {};
YT_ready(function() {
    $("li.video iframe.youtube").each(function(event) {
        var frameID_homepage = $(this).attr('id');
        if (frameID_homepage) {
            players_homepage[frameID_homepage] = new YT.Player(frameID_homepage, {
                events: {
                    'onStateChange': onPlayerStateChange_homepage
                }
            });
        }
    });
});
(function(){
    var tag = document.createElement('script');
    tag.src = "//www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
})();

function onPlayerStateChange_homepage(event) {
    if (event.data === 0) {
        // do something on end
    } else if (event.data === 1) {
        // do something on play
    } else if (event.data === 2) {
        // do something on pause
    }
}

function pauseVideo_homepage(previousVideo) {
    players_homepage[previousVideo].pauseVideo();
}
function playVideo_homepage(currentVideo) {
    players_homepage[currentVideo].playVideo();
}

0 个答案:

没有答案