微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用 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 可能随时更改,恕不另行通知。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。