在这个jsfiddle中http://jsfiddle.net/StephanieQ/oo1g1762/
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement("script");
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player("player", {
"height": "315",
"width": "560",
"videoId": "bHQqvYy5KYo",
"events": {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event){
var time;
time = player.getCurrentTime();
$("#timeHolder").text(time);
}
我正在使用youTube的播放器对象方法player. getcurrenttime ();来查看嵌入在youTube视频中的时间。正如你所看到的,每次播放器状态改变时,"时间"被重新定义并插入到timeHolderdiv中。有没有办法让"时间"被连续定义,以便它与当前时间匹配,并在更新时插入到div中?(不被玩家状态改变触发?)
更重要的是,我正在玩这个,因为我想能够使用youTube视频上的当前时间与其他外部脚本进行交互,我怎么能使它全局?
使用setInterval()
重复该函数。甚至当。Data = 1表示YouTube正在播放,所以让这个函数重复。否则不播放,则使用clearInterval()
停止重复播放功能。
var myTimer;
function onPlayerStateChange(event){
if(event.data==1) { // playing
myTimer = setInterval(function(){
var time;
time = player.getCurrentTime();
$("#timeHolder").text(time);
}, 100); // 100 means repeat in 100 ms
}
else { // not playing
clearInterval(myTimer);
}
}
见此处