如何使用 YouTube IFrame Player API 收听时间变化事件?

How to listen to time change events with the YouTube IFrame Player API?

我找不到在 YouTube IFrame 播放器 API 上收听时间变化的任何方法(因此我可以在我的 UI 中显示当前 time/duration 的视频)文档。有没有办法不用轮询就可以做到这一点 getCurrentTime()?

YouTube IFrame 播放器 API 没有提供任何方式来监听时间变化更新,但由于它在内部使用 postMessage 事件在 IFrame 和主 window, 你可以给你的 window 添加一个监听器来监听它们并且只对时间变化的做出反应:

// 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.
        }
      }
    }
  });
}

See it live.

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