gpt4 book ai didi

javascript - 如何监听youtube iframe的音量变化?

转载 作者:行者123 更新时间:2023-12-03 02:50:18 25 4
gpt4 key购买 nike

Here我找到了一个如何监听 YouTube iframe 的“播放\暂停”按钮的示例。

player.addEventListener('onStateChange', function(e) {
console.log('State is:', e.data);
});

现在我需要听音量变化。在 YouTube 文档和 here 中我找到了一个方法player.getVolume() ,但如果我想从 iframe 端获知音量变化,而不是从我这边询问 iframe,我不知道如何实现此方法。

On YouTube Player Demo page存在这样的功能(当我更改播放器的音量时,我在 Volume, (0-100) [current level: **] 行中看到适当的更改),但 in the doc 都没有。在互联网上我也找不到如何实现它。

我还尝试将上述代码与 onApiChange 一起使用事件(我不清楚这个事件实际上做了什么),例如:

player.addEventListener('onApiChange', function(e) {
console.log('onApiChange is:', e.data);
});

但控制台没有显示任何新内容。

player.getOptions();显示Promise {<resolved>: Array(0)} .

谁能举个例子吗?

最佳答案

参见this question .

您可以监听 IFrame 发出的 postMessage 事件,并仅对音量变化事件使用react:

// 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;

// 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 volume change.
if (
data.event === "infoDelivery" &&
data.info &&
data.info.volume
) {
console.log(data.info.volume); // there's also data.info.muted (a boolean)
}
}
});
}

See it live .

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

关于javascript - 如何监听youtube iframe的音量变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47897370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com