youtube API playVideo, pauseVideo and stopVideo not working

后端 未结 1 1103

I\'m attempting to use the YouTube API to control a set of players in a slideshow. I want to be able to stop and play videos depending on which frame the slideshow is on. So I\'

相关标签:
1条回答
  • 2021-01-26 13:09

    A couple of things I see going on that may be of use. First of all, removing the origin parameter will help during development, as it prevents access to the API in general if A) it doesn't match exactly, and B) sometimes for no reason when on localhost.

    As you note, though, even when removing it in your case the API isn't responding. This is because creating a YT.player object consumes a bit of time, and so you then are trying to trigger a playVideo method before the object is fully initialized. Instead you should utilize the onReady callback parameter of the YT.Player object, like this:

        var tag = document.createElement('script');
        tag.src = "//www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        var yt_players = {};
    
        function onYouTubeIframeAPIReady() {
            yt_players['1-5'] = new YT.Player('ytplayer_1-5', {
              events: {'onReady': onPlayerReady} // bind to callback for when object is ready
            });
        }
    
        function onPlayerReady(event) {
            event.target.playVideo(); // this is kept generic so the same callback can be used with any player object
        }
    

    Here's a fiddle with the working code: http://jsfiddle.net/jlmcdonald/dEjXL/

    0 讨论(0)
提交回复
热议问题