如何使用YouTube IFrame Player API收听时间更改事件? [英] How to listen to time change events with the YouTube IFrame Player API?

查看:138
本文介绍了如何使用YouTube IFrame Player API收听时间更改事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I couldn't find any way to listen to time changes (so I can show a current time/duration of the video in my UI) on the YouTube IFrame Player API documentation. Is there a way to do this without polling getCurrentTime()?

推荐答案

YouTube IFrame Player API并未提供任何监听时间更改更新的方法,但是由于其内部使用了

The YouTube IFrame Player API doesn't expose any way to listen for time change updates, but since internally it uses postMessage events to communicate between the IFrame and the main window, you can add a listener to your window to listen to them and react only to the time change ones:

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

实时观看.

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

Note that this relies on a private API that may change at anytime without previous notice.

这篇关于如何使用YouTube IFrame Player API收听时间更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆