开发者

Timer "along" with Youtube clip with JS to show divs at different times

I want to load a youtube clip on a page, and along with the clip I want to add a top (HTML) layer that will work somewhat like youtube's own annotation functionality.

In bullets: - User will see a YT clip (probably in a custom player) - Depending on the current time of the clip, I need JS to load information on a layer on top of the clip.

So: For example, from 0.00 to 0.05 you see a piece of text on top of the clip From 0.05 to 0.30 no text From 0.30 to 0.37 text 开发者_StackOverflowagain etc etc

Any ideas on how to approach this? I realize Youtube's Player API has the functionality to getCurrentTime But how would I go on write a piece of JS to "play along" with the clip on a div layer on top of the clip?


The way to achieve this is indeed to do with the getCurrentTime method on the yt api, specifically, call it in a repeating function with the help of setInterval.

You will need to keep an array of overlays you wish to present, along with the from and to time, something like:

var overlays = [
    {text:"Some text",from:1,to:6},
    {text:"Some other text",from:8,to:14}];

Then, you'll need a couple of functions to handle the movie playing and stoping (or pausing).

var watchId;
function startWatch(){
    watchId = setInterval( function(){
        showOrHideOverlay(ytplayer.getCurrentTime());
    },1000)
}

function stopWatch(){
  clearTimeout(watchId);
}

You'll notice that uses a variable ytplayer and according to the jsapi documentation this can be grabbed using the following code:

var ytplayer ;
function onYouTubePlayerReady(playerId) {       
    ytplayer = document.getElementById("myytplayer");  
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");   
}

Notice in there ive attached an event listener, this leads us to a method to handle the movie state changing

function onytplayerStateChange(newState) {    
    if(newState == 1){ // playing
         startWatch()
    }
    else if(newState == 0 || newState == 2){ //ended or paused
         stopWatch();   
    }            
}

So the last piece of the puzzle is actually handling a "tick" which ive set to occur every second. This method showOrHideOverlay looks like:

function showOrHideOverlay(time){
    // find overlays which should be visible at "time"
    var shownOverlays = false;
    for(var i=0;i<overlays.length;i++){
        if(overlays[i].from < time && overlays[i].to > time){
            $('#overlay').text(overlays[i].text);
            shownOverlays = true;
        }           
    }
    if(!shownOverlays)
        $('#overlay').text("");

}

Finally, the live example: http://jsfiddle.net/zTZjU/ (Just press play on the clip)


Check this fiddle: http://jsfiddle.net/rEeJS/
I added wmode="transparent" to allow the overlay to appear in Chrome.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜