在播放时获取 YouTube 视频的当前时间

问题描述 投票:0回答:3

当我播放这样的 Youtube 视频时:

https://www.youtube.com/tv?#/watch/video/control?v=d1-VK12FZhs&resume&t=0m4s

我在视频底部看到播放时间和持续时间。

我可以在页面中查找此内容来了解当前播放时间:

< span class="ytp-time-current">0:11

过了一会儿,此信息就会被隐藏,直到我再次将鼠标指针移到视频上。

显示信息时,我可以获得每秒更新的 ytp-time-current 值。 当信息隐藏时,该值不会更新。 如何在信息隐藏的情况下获取当前时间?

我在 Chrome 扩展程序中使用此代码:

document.addEventListener("spfdone", process); 
document.addEventListener("DOMContentLoaded", process); 

function process(){ 
stop(); 
start(); 
} 
window.onbeforeunload = function () { 
stop(); 
}; 

function start(){ 

x2 = setInterval(function() { 

// here is the place to use the solution i'm looking for

},1000); 
} 

function stop(){ 
}

提前致谢。

javascript html youtube
3个回答
2
投票

根据 YouTube iframe api 您可以使用:getCurrentTime()

在chrome控制台中编写以下代码即可:

document.querySelector('.video-stream').getCurrentTime()

0
投票

这是您想要显示的内容的完整解决方案:

var player = document.getElementById('movie_player');
var time = player.getCurrentTime();
var sec_num = parseInt(time, 10);
var hours   = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10)
   hours = '0' + hours;
if (minutes < 10)
   minutes = '0' + minutes;
if (seconds < 10)
   seconds = '0' + seconds;
alert(hours + ':' + minutes + ':' + seconds);

0
投票

如果你使用react,你可以使用react-youtube

    <ReactPlayer
      height='200'
      width='100%'
      url={`https://www.youtube.com/embed/${youtubeId}?&autoplay=1`}
      config={{
        youtube: {
          playerVars: {
            autoplay: 1,
            controls: 0,
            rel: 0,
            showinfo: 0,
            mute: 0,
            loop: 1
          }
        }
      }}
      onProgress={(e) => console.log(e)}
    />
© www.soinside.com 2019 - 2024. All rights reserved.