如何使用 YouTube IFrame Player API 监听时间更改事件?

Fel*_*van 5 javascript youtube iframe youtube-iframe-api

我在 YouTube IFrame Player API 文档上找不到任何方法来监听时间变化(因此我可以在 UI 中显示视频的当前时间/持续时间)。有没有办法在不轮询的情况下做到这一点getCurrentTime()

Fel*_*van 6

YouTube IFrame 播放器 API 不公开任何方式来侦听时间更改更新,但由于它在内部使用postMessage事件在 IFrame 和主窗口之间进行通信,因此您可以向窗口添加一个侦听器来侦听它们并仅对以下内容做出反应时间变化的:

// Instantiate the Player.
function onYouTubeIframeAPIReady() {
  var player = new YT.Player("player", {
    height: "390",
    width: "640",
    videoId: "dQw4w9WgXcQ"
  });

  // This is the source "window" that will emit the events.
  var iframeWindow = player.getIframe().contentWindow;

  // So we can compare against new updates.
  var lastTimeUpdate = 0;

  // Listen to events triggered by postMessage.
  window.addEventListener("message", function(event) {
    // Check that the event was sent from the YouTube IFrame.
    if (event.source === iframeWindow) {
      var data = JSON.parse(event.data);

      // The "infoDelivery" event is used by YT to transmit any
      // kind of information change in the player,
      // such as the current time or a playback quality change.
      if (
        data.event === "infoDelivery" &&
        data.info &&
        data.info.currentTime
      ) {
        // currentTime is emitted very frequently,
        // but we only care about whole second changes.
        var time = Math.floor(data.info.currentTime);

        if (time !== lastTimeUpdate) {
          lastTimeUpdate = time;
          console.log(time); // update the dom, emit an event, whatever.
        }
      }
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

现场观看

请注意,这依赖于私有 API,该 API 可能随时更改,恕不另行通知。