如何在播放视频时更新视频的当前时间?

How can I update current time of the video while it's playing?

开始播放视频后的每一秒,我希望它 运行 调用 showComments

的函数

为了确保每秒 运行ning,我刚刚添加了

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>

您可以使用 setInterval 到 运行 每 1000ms(1s) 的函数,并结合 onStateChange 事件。 每当事件触发时,它都会检查视频是否正在播放。如果正在播放,它开始每秒调用 showComments 函数。否则它会停止间隔。

工作fiddle: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.";
}