无法从多个YT.Player实例中正确控制单个视频

时间:2018-08-08 15:39:53

标签: youtube-iframe-api

我正在使用一个浏览器扩展程序,该扩展程序将允许您启用/禁用嵌入式YouTube视频上的字幕。总的来说,我已经能够通过内容脚本与页面上运行的注入脚本进行通信来使其工作。问题是,当已经有一个针对视频运行的YT.Player实例时,只有一个能够正确控制它。请参见以下类似案例的jsfiddle示例。

https://jsfiddle.net/xpvt214o/573198/

var initPlayer = function (name, playerID, toggleSelector) {
    console.log("Create Player: " + name);
    var that = {};
    that.name = name;
    that.model = {
        captions: undefined,
        prepped: false
    };

    that.toggle = $(toggleSelector);
    that.player = new YT.Player("existing-iframe-example", {
        events: {
            "onApiChange": function () {
                console.log("onApiChange fired for " + that.name);
                prepPlayer(that);
            }
        }
    });

    return that;
}

var toggleCaptions = function (that) {
    console.log("Toggling captions for Player " + that.name);
    if (that.model.captions === undefined) {
        that.model.captions = that.model.captions = !!that.player.getOption("captions", "track").languageCode;
    }
    if (that.model.captions) {
        that.player.setOption("captions", "track", {});
        that.model.captions = false;
    } else {
        var track = that.player.getOption("captions", "tracklist")[0];
        that.player.setOption("captions", "track", track);
        that.model.captions = true;
    }
};

var prepPlayer = function (that) {
    if (!that.model.prepped) {
        console.log("Prepping Player " + that.name);
        that.player.loadModule("captions");
        that.toggle.on("click", function () {
            toggleCaptions(that);
        });
        that.toggle.prop("disabled", false);
        that.toggle.removeAttr("disabled");
        that.model.prepped = true;
    }
};

var createPlayers = function () {
    initPlayer("Player 1", "existing-iframe-example", ".player1");
    initPlayer("Player 2", "existing-iframe-example", ".player2");
};



if (window.YT && window.YT.Player) {
    console.log("create players");
    createPlayers();
} else {
    console.log("wait for YT Api");
    // the YouTube iframe api will call onYouTubeIframeAPIReady after the api has loaded
    window.onYouTubeIframeAPIReady = function () {
            createPlayers();
    }
}

注意:在示例中,播放视频后,切换按钮应变为可用。注意,由于loadModule函数不可用,将引发错误。您可以通过注释掉任一播放器初始化功能来使事情正常进行。

以上内容还假设您为api <script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>添加了脚本标签,并且存在一个ID为existing-iframe-example的视频。

0 个答案:

没有答案