偉大的,非常酷的東西,我解決了我的問題,這裏是我的問題的答案。
我用的YouTube API的幫助,從這個js小提琴http://jsfiddle.net/oo1g1762/1/
var myTimer;
// 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){
if(event.data==1) { // playing
myTimer = setInterval(function(){
var time;
time = player.getCurrentTime();
$("#timeHolder").text(time);
}, 100);
}
else { // not playing
clearInterval(myTimer);
}
}
這是這個問題的答案YouTube API - Getting current time in a global variable
這裏是我自己的代碼
var myTimer;
// 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", {
"videoId": "D3C3mAub0vA", //Here is the video ad ID
"events": {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// Countdown timer
var time;
function onPlayerStateChange(event){
if(event.data==1) { // playing
var counter = 10;
myTimer = setInterval(function(){
time = Math.floor(player.getCurrentTime());
if (time >= 0) {
counter--;
if (counter == 0) {
$('#skip-counter').hide(); // Hide counter
$('#skip').fadeIn(); // Show skip ad button
clearInterval(myTimer); // End interval function
}
else {
$('#timer').text(counter); // Printing time
}
}
}, 1000);
}
else { // not playing
clearInterval(myTimer);
}
}