获取播放器的当前状态(Youtube API)

时间:2017-04-02 05:54:04

标签: youtube youtube-javascript-api

是否有任何函数可以获取Youtube API播放器的当前状态? 如果玩家当前状态为1(正在播放),我想编写一个运行命令的函数,但我无法在参考页面上找到任何内容。
p / s:我已经知道了onStageChange,我需要检查当前状态 我的创建播放器代码:

var player;
    window.onYouTubeIframeAPIReady = function () {
        console.log('onYouTubeIframeAPIReady');
        player = new YT.Player('video_player', {
            // playerVars: { 'enablejsapi':1,'autoplay':0,'controls':0,'rel':0,'showinfo':0,'egm':0,'showsearch':0,'modestbranding':1,'iv_load_policy':3,'disablekb':0,'loop':0},
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange,
                'onError': onPlayerError
            }
        });
    }

1 个答案:

答案 0 :(得分:2)

#通过onStateChange

API触发事件以通知您的应用程序有关内置播放器的更改。对于以下每种类型的状态,API都会将事件对象作为唯一的对象传递:

  • YT.PlayerState。ENDED 0
  • YT.PlayerState.PLAYING 1
  • YT.PlayerState.PAUSED 2
  • YT.PlayerState.BUFFERING 3
  • YT.PlayerState.CUED 5

示例:

   ...

   onPlayerStateChange(event) {

        if (event.data == YT.PlayerState.ENDED) {               
            console.log("Video Ended");
        }

        if (event.data == YT.PlayerState.PLAYING) {             
            console.log("Video Playing");
        }

        if (event.data == YT.PlayerState.PAUSED) {              
            console.log("Video Paused");
        }

        if (event.data == YT.PlayerState.BUFFERING) {               
            console.log("Video Buffering");
        }

        if (event.data == YT.PlayerState.CUED) {                
            console.log("Video Cued");
        }

    },

    ...

#通过getPlayerState()

  var player;

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '360',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  console.log(player.getPlayerState());

getPlayerState()的可能值为:

  • -1 –未启动
  • 0 –已结束
  • 1 –玩
  • 2 –暂停
  • 3 –缓冲
  • 5 –提示