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

问题描述

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

解决方法

YouTube IFrame Player 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.
        }
      }
    }
  });
}

See it live

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