2

单击链接时,我正在尝试播放 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");

                 }

             }

           }
        );
4

1 回答 1

2

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

示例: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>
于 2013-08-13T23:52:12.700 回答