加载YouTube视频并收听onPlayerStateChange



单击链接时,我正在尝试播放YouTube视频,并在播放完后用图像替换该视频。

上半场很轻松。然而,我在下半场遇到了麻烦。最初,我只是添加了一个iframe嵌入。然而,为了收听ENDED事件,我尝试遵循YouTube开发文档。现在,我似乎什么都做不了。请复习。这就是我迄今为止所拥有的。

 var t1 = '<div id="tubewrapper"><div id="player"></div></div>'

$("#link").click( function()
           {
             
             $(".trailers-band").append(t1);

    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('player',{
                       height:'100%',
                       width:'100%',
                       videoId:tubeID,
                       events:{
                           'onReady': onPlayerReady,
                           'onStateChange': onPlayerStateChange
                       }
                   });
               }
            function onPlayerReady(event){
                alert("ready");
                event.target.playVideo();
            }
             var done = false;
             function onPlayerStateChange(event){
                 if (event.data == YT.PlayerState.ENDED && !done){
                     done = true;
                     alert("done");
                 }
             }
           }
        );

以下是如何播放视频、检测视频何时结束,然后在其位置显示图像的示例。

示例:jsFiddle

<div id="player" style="display:none;"></div>
<a href="#" id="link">play</a>
<script>
// Load API asynchronously.
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('player', {
        height: '390',
        width: '640',
        videoId: '9vHFsXOdTt0',
        events: {'onStateChange': onPlayerStateChange}
    }); // create the <iframe> (and YouTube player)
}
function onPlayerStateChange(event) {    
    if(event.data === 0) {          
        hideVideo();
    }
}
function hideVideo() {
    var img_url = 'https://www.google.com/images/srpr/logo4w.png';
    $('#player').replaceWith('<img src="'+img_url+'">');
}
$("#link").click(function(){
    $('#player').show(); // show player
    player.playVideo(); // begin playback
});
</script>

相关内容

  • 没有找到相关文章

最新更新