我在 YouTube IFrame Player API 文档上找不到任何方法来监听时间变化(因此我可以在 UI 中显示视频的当前时间/持续时间)。有没有办法在不轮询的情况下做到这一点getCurrentTime()
?
YouTube IFrame Player API 没有公开任何监听时间更改更新的方法,但由于它在内部使用postMessage https://developer.mozilla.org/en-US/docs/Web/API/Window/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.
}
}
}
});
}
现场观看 https://codepen.io/zavan/pen/PoGQWmG.
请注意,这依赖于私有 API,该 API 可能随时更改,恕不另行通知。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)