我已在 iframe 中嵌入了 YouTube 播放器。我想在视频开始播放之前了解视频的时长,或者希望在时长从 0 更新为实际时长时收到通知。这怎么办?
谢谢。
根据 Google YouTube api...
检索视频信息
player.getDuration():数字 返回当前播放视频的持续时间(以秒为单位)。请注意,getDuration() 将返回 0,直到加载视频的元数据,这通常发生在视频开始播放后。
如果当前播放的视频是直播事件,则 getDuration() 函数将返回自直播视频流开始以来经过的时间。具体来说,这是视频在没有重置或中断的情况下流式传输的时间量。此外,此持续时间通常比实际事件时间长,因为流媒体可能会在事件开始时间之前开始。
enablejsapi=1
参数才能工作。onYouTubeIframeAPIReady
的函数,该函数将在加载 API 库时调用。player.getDuration()
获取持续时间(以秒为单位)。<script src="https://www.youtube.com/iframe_api"></script>
<iframe id="player" width="560" height="315" src="https://www.youtube.com/embed/aqz-KE-bpKQ?enablejsapi=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
function onYouTubeIframeAPIReady() { // function that will be called by the API library
const player = new YT.Player("player", { // "player" is the id of the iframe
events: {
"onReady": (event) => {
console.log(`Duration of "${player.videoTitle}": ${player.getDuration()} sec`)
},
}
});
}
// check if API library was already loaded and in that case execute the function yourself
if (window.YT?.Player) {
onYouTubeIframeAPIReady();
}
您可以在官方 YouTube 的 iFrame API 文档中阅读有关 API 使用的更多信息。