无法触发 Youtube 的 Iframe-API – 未定义的 "loadVideoByUrl('...')"

Cannot fire "loadVideoByUrl('...')" of Youtube's Iframe-API – undefined

看来我在这里遗漏了一些明显的东西,但我无法得到

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('player1');
    // here everything is fine and I can see the 
    // function as part of player
    console.log(player);
    // but here it says "player.loadVideoByUrl()" undefined
    player.loadVideoByUrl("https://youtu.be/bHQqvYy5KYo");
    player.playVideo();
}

上班。有什么想法吗?

提前致谢!

我假设在您调用 loadVideoByUrl 函数时 player 没有初始化。在文档中,他们使用

events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }

玩家事件。播放器对象似乎是异步构造的。因此,如果您使用这些事件,代码将如下所示:

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('player1', {
      events: {
        'onReady': onPlayerReady
      }
    });
}

function onPlayerReady(){
     player.loadVideoByUrl("https://youtu.be/bHQqvYy5KYo");
     player.playVideo();
}