gpt4 book ai didi

javascript - 当 youtube 视频开始播放时,有什么方法可以用 javascript 检测吗?

转载 作者:行者123 更新时间:2023-11-29 19:16:09 26 4
gpt4 key购买 nike

嵌入式 youtube iframe 是否有视频的“加载”?

我只想在我选择的音乐视频开始播放后才开始我的脚本。

我已将一个 onload 事件粘贴到 iframe 上,YouTube 视频在其中传送,但这与实际视频的加载(缓冲已完成准备播放)不对应。它仅对应于视频播放器已加载到页面中的时间。

换句话说,有什么方法可以用 javascript 检测 youtube 视频何时开始播放?

最佳答案

您正在寻找的一切都可以在 Youtube Iframe API reference 中找到.

我也会在这里粘贴相关代码,但请注意,我只修改了一行以触发 onReady 警报。其余代码来自上述引用页面。

<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
alert("Video Ready!");
event.target.playVideo(); // You can omit this to prevent the video starting as soon as it loads.
}

// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>

关于javascript - 当 youtube 视频开始播放时,有什么方法可以用 javascript 检测吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35192346/

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