YouTube JavaScript API, on状态更改未触发,无自动播放

我有一个训练计划,我尝试在 iFrame 中显示 YouTube 视频,自动播放它,并在视频完成后前进到下一页。我可以让YouTube上IPFI就绪函数触发,但其他事件都不会。实际上,我只对状态变化感兴趣。


    var tag = document.createElement('script');

    tag.src = 'https://www.youtube.com/iframe_api';

    tag.id = 'apiScript';

    var firstScriptTag = document.getElementsByTagName('script')[0];

    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

...


    //function onYouTubeIframeAPIReady() {  //tried this too but no change

    window.onYouTubeIframeAPIReady = function() {

        player = new YT.Player('externalComponent', {

        events: {

            'onReady': onPlayerReady,

            'onError': onPlayerError,

            'onStateChange': onPlayerStateChange

            }

        });

        console.log('api ready');

    }


    function onPlayerStateChange(event) {

        console.log('onStateChange');

        console.log(YT.PlayerState);

    }

当它运行时,您可以在控制台中看到“api就绪”,但没有其他内容。内联框架如下所示:


    <iframe id="externalComponent" src="https://youtube.com/embed/_S_Bg9qfa8o?enablejsapi=1&controls=0&autoplay=1" width="1024" height="576" allow="autoplay" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

是什么阻止了 onState更改了工作状态,而不是自动播放?控件不显示。


泛舟湖上清波郎朗
浏览 143回答 1
1回答

喵喔喔

我无法让它像我发布的那样工作。我不得不更改代码以使用div而不是iframe,在播放器Vars中添加视频ID和其他参数。完成此操作后,视频会自动播放,不显示任何控件,并触发状态更改事件。&nbsp; function onYouTubeIframeAPIReady() {&nbsp; &nbsp; player = new YT.Player('player', {&nbsp; &nbsp; &nbsp; playerVars: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; autoplay: 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controls: 0,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showinfo: 0,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; autohide: 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; videoId: '_S_Bg9qfa8o',&nbsp; &nbsp; &nbsp; events: {&nbsp; &nbsp; &nbsp; &nbsp; 'onReady': onPlayerReady,&nbsp; &nbsp; &nbsp; &nbsp; 'onStateChange': onPlayerStateChange&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; }...<div id="player"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript