javascript - How to listen to time change events with the YouTube IFrame Player API? - Stack Overflow

I couldn't find any way to listen to time changes (so I can show a current timeduration of the vi

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()?

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()?

Share Improve this question edited Dec 30, 2020 at 19:19 Felipe Zavan asked Dec 30, 2020 at 18:03 Felipe ZavanFelipe Zavan 1,8331 gold badge20 silver badges34 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

The YouTube IFrame Player API doesn't expose any way to listen for time change updates, but since internally it uses postMessage events to municate 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 pare 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.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745288770a4620727.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信