在开始播放视频后的每一秒,我都希望它能够运行名为 showComments
的功能为了确保它每秒都在运行,我刚刚添加了
alert(getCurrentTime().toFixed());
但是,它甚至没有运行:(
如何每秒运行 showComments 功能?
这是演示和代码。
演示:https://jsfiddle.net/f0buajyz/
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '270',
width: '480',
videoId: 'mzIdhSTHJts',
});
}
var fixedTimeHtml5Youtube = 0;
function getStatus(){
if(player.getCurrentTime().toFixed() != fixedTimeHtml5Youtube){
alert(getCurrentTime().toFixed());
showComments(player.getCurrentTime().toFixed());
fixedTimeHtml5Youtube = player.getCurrentTime().toFixed();
}
}
</script>
答案 0 :(得分:3)
您可以使用setInterval每1000毫秒(1秒)运行该功能,并结合onStateChange
事件。
每当事件触发时,它都会检查视频是否正在播放。如果正在播放,它会每秒开始调用showComments
函数。否则它会停止间隔。
工作小提琴:https://jsfiddle.net/crisbeto/f0buajyz/4/
HTML:
<div id="player"></div>
<textarea id="output"></textarea>
JavaScript的:
var tag = document.createElement('script');
var player = null;
var interval = null;
tag.src = "https://www.youtube.com/iframe_api";
document.body.appendChild(tag);
window.onYouTubeIframeAPIReady = function(){
player = new window.YT.Player(document.getElementById('player'), {
height: '270',
width: '480',
videoId: 'mzIdhSTHJts',
events: {
onStateChange: function(event){
callback(event);
}
}
});
}
function callback(event){
var playerStatus = event.data;
// player is playing
if(playerStatus === 1){
interval = setInterval(showComments, 1000);
// player is stopped
}else if(interval){
clearInterval(interval);
}
}
function showComments(){
document.getElementById('output').value += "\n showComments called.";
}