Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Youtube API event on a specified time

Tags:

youtube

api

Is it possible through the YouTube API to fire an event when the video reaches a specified time? e.g. when the video reaches 20 sec. fire the event.

Thanks,
Mauro

like image 401
Mauro74 Avatar asked Apr 16 '12 13:04

Mauro74


1 Answers

not sure if you still need an answer to this (as I'm finding it 4 months later) but here's how I accomplished this with youtube's iframe embed api. It's ugly in that it requires a setInterval, but there really isn't any kind of "timeupdate" event in the YouTube API (at least not in the iframe API), so you have to kind of fake it by checking the video time every so often. It seems to run just fine.

Let's say you want to start up your player as shown here with YT.Player(), and you want to implement your own onProgress() function that is called whenever the video time changes:

In HTML:

<div id="myPlayer"></div>

In JS:

// first, load the YouTube Iframe API:
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// some variables (global here, but they don't have to be)
var player;
var videoId = 'SomeYoutubeIdHere';
var videotime = 0;
var timeupdater = null;

// load your player when the API becomes ready
function onYoutubeIframeAPIReady() {
  player = new YT.Player('myPlayer', {
    width: '640',
    height: '390',
    videoId: videoId,
    events: {
      'onReady': onPlayerReady
    }
  });
}

// when the player is ready, start checking the current time every 100 ms.
function onPlayerReady() {
  function updateTime() {
    var oldTime = videotime;
    if(player && player.getCurrentTime) {
      videotime = player.getCurrentTime();
    }
    if(videotime !== oldTime) {
      onProgress(videotime);
    }
  }
  timeupdater = setInterval(updateTime, 100);
}

// when the time changes, this will be called.
function onProgress(currentTime) {
  if(currentTime > 20) {
    console.log("the video reached 20 seconds!");
  }
}

It's a little sloppy, requiring a few global variables, but you could easily refactor it into a closure and/or make the interval stop and start itself on play/pause by also including the onStateChange event when you initialize the player, and writing an onPlayerStateChange function that checks for play and pause. You'd just need to seperate the updateTime() function from onPlayerReady, and strategically call timeupdater = setInterval(updateTime, 100); and clearInterval(timeupdater); in the right event handlers. See here for more on using events with YouTube.

like image 92
Mike Turley Avatar answered Sep 22 '22 20:09

Mike Turley