如何让2个YouTube视频自动逐个播放?

时间:2015-09-04 19:49:19

标签: javascript jquery css video youtube

我试图找出如何让2个视频一个接一个地自动播放,即第一个视频完成后,第二个视频开始播放。如何才能做到这一点? http://jsfiddle.net/neowot/8hc3mf27/

HTML

<div class="videowrapper">
            <iframe src="https://www.youtube.com/embed/zgQaEAhMIOI" frameborder="0" allowfullscreen></iframe>
</div>

<div class="videowrapper">
            <iframe src="https://www.youtube.com/embed/zgQaEAhMIOI" frameborder="0" allowfullscreen></iframe>
</div>

CSS

.videosetter{

}
.videowrapper {
    /*float: none;
    clear: both;
    width: 100%;
    height:100%;
    position: absolute;
    background-color:blue;
    padding-bottom: 56.25%;
    padding-top: 25px;
    height: 0;*/
}
.videowrapper iframe {
    position: relative;
    top: 2px;
    left: 12px;
    margin-bottom:3px;
    margin-left:0px; 
    width:250px;
    height:145px;   
    border-width:1px;
    border-style:solid;
    border-color:black;
}

的jQuery

$(document).ready(function() {
    this.player = new YT.Player('player', {
        height: pxHeight,
        width: pxWidth,
        playerVars: {
            'rel': 0,
            'controls': 0,
            'fs':0
        },
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange,
            'onError': onError
        }
    });

    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING) {
            LOG("Youtube Playing");
        } else if (event.data == YT.PlayerState.ENDED) {
            LOG(">>>Youtube Ended");
            this.player.loadVideoById(ID, 0, "default");
        } else if (event.data == YT.PlayerState.PAUSED) {
            LOG("Youtube Paused");
        } else if (event.data == YT.PlayerState.BUFFERING) {
            LOG("Youtube Buffering");
        } else if (event.data == YT.PlayerState.CUED) {
            LOG("Youtube Cued");
        }
    }

});

1 个答案:

答案 0 :(得分:2)

我在第一个视频播放结束后立即播放第二个视频jsFiddle

var player1, player2;
function onYouTubeIframeAPIReady() {
    player1 = new YT.Player('player1', {
      height: '195',
      width: '320',
      videoId: 'zgQaEAhMIOI',
      events: {
        'onReady': onPlayer1Ready,    //Called first
        'onStateChange': onPlayer1StateChange //Called when #player1 state changes
      }
    });
    player2 = new YT.Player('player2', {
      height: '195',
      width: '320',
      videoId: 'zgQaEAhMIOI',
      events: {
        'onReady': null,        //Set to null as it is controlled by #player1 
        'onStateChange': null   //Set to null as it is controlled by #player1 
      }
    });
  }

  function onPlayer1Ready(event) {
    event.target.playVideo();
  }

  function onPlayer1StateChange(event) {
    if (event.data == YT.PlayerState.ENDED) { //When #player1 video ends,
      player2.playVideo();                    //#player2 video starts
    }
  }

完全基于YouTube API