检查youtube api播放器是否已暂停

时间:2019-01-13 16:58:42

标签: javascript youtube-api

我创建了一个按钮,可在点击后暂停并播放youtube视频。我正在尝试检查视频是否已经暂停(如果正在播放),如果正在播放则暂停。 isPaused不是函数。我正在寻找什么功能?

document.getElementById("playButton").addEventListener('click', function (event) {
    if(!!player.isPaused()){
        player.playVideo();
    } 
    else {
        player.pauseVideo();
    }
});

1 个答案:

答案 0 :(得分:0)

在没有有关HTML控件的模式详细信息的情况下,我认为您正在使用HTML元素来控制视频的再现(播放)和暂停功能。

如果是这样,则必须在onPlayerStateChange函数中,将逻辑设置如下:

// 5. The API calls this function when the player's state changes.
function onPlayerStateChange(event) {

  // If the video is PLAYING, set the onclick element for pause the video.
  // Once the "playButton" is clicked, the video will be paused.
  if (event.data == YT.PlayerState.PLAYING) {
    document.getElementById('playButton').innerHTML = 'Pause';

    // Set the onclick event to the button for pause the YouTube video.
    document.getElementById('playButton').onclick = function() {
      player.pauseVideo();
    };
  }

  // If the video is PAUSED, set the onclick element for pause the video.
  // Once the "playButton" is clicked, the video will resume the video = continue playing the video.
  if (event.data == YT.PlayerState.PAUSED) {
    document.getElementById('playButton').innerHTML = 'Play';
    document.getElementById('playButton').onclick = function() {
      player.playVideo();
    };
  }
}

此功能已从YouTube Player API documentation中的可用示例代码中进行了修改。

这里是working jsfiddle example