如何将新ID传递给YouTube播放器(以自动播放第二个视频?)

时间:2015-07-31 22:48:40

标签: youtube youtube-javascript-api

我正在尝试创建

页面
  1. 选择随机视频(来自ID数组 - 我有ID并可以选择它们)
  2. 播放该视频
  3. 播放另一个随机视频(抓住另一个ID
  4. 我所坚持的部分是将一个不同的ID传递给已经存在的YouTube播放器。

    所以当我有这样的事情时:

    <div id="player"></div>
    
    <script src="http://www.youtube.com/player_api"></script>
    
    <script>
    
    // create youtube player
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'zmr2I8caF0c',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
    }
    
    // autoplay video
    function onPlayerReady(event) {
        event.target.playVideo();
    }
    
    // when video ends
    function onPlayerStateChange(event) {        
        if(event.data === 0) {            
            event.target.playVideo();
            //how do I pass a new ID here ^
        }
    }
    

    如何将新ID传递给event.target.playVideo()?我可以创建一个将ID作为参数并以某种方式传递它的函数吗?

1 个答案:

答案 0 :(得分:0)

想出来。

<div id="player"></div>

<script src="http://www.youtube.com/player_api"></script>

<script>

    var videos = [
      '3H3odKtfrTo',
      'BxjMGiN0jJY',
      'iGC9n0NAvDU'
    ]


    var index=Math.floor(Math.random() * videos.length);

    // create youtube player
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: '9yT7KcHCrRY',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
    }

    // autoplay video
    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function playNewVideo(id){
      player.loadVideoById(videos[index]);
      event.target.playVideo();
      playNewVideo(randomID)
    }

    // when video ends
    function onPlayerStateChange(event) {        
        if(event.data === 0) { 
          //generate new random number
          index=Math.floor(Math.random() * videos.length);
          playNewVideo();
        }
    }

</script>