Last active
November 11, 2015 03:52
-
-
Save owenroberts/3255401a58c175e1abb2 to your computer and use it in GitHub Desktop.
YouTube API Example JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var tag = document.createElement('script'); | |
tag.src = "http://www.youtube.com/iframe_api"; | |
var firstTagScript = document.getElementsByTagName('script')[0]; | |
firstTagScript.parentNode.insertBefore(tag, firstTagScript); | |
var subtitles = ["Hello!", "I'm a cat!", "Goodbye!"]; | |
var currentSubtitle = 0; | |
var subtitleInterval = 10; | |
var $subtitles = $('#subtitles'); | |
var backgroundColors = ["blue", "red", "pink"]; | |
var currentBackground = 0; | |
var backgroundInterval = 3; | |
var $body = $('body'); | |
var $catgif = $('<img>') | |
.attr({ | |
src:'http://www.catgifs.org/wp-content/uploads/2013/09/122_yawn_cat_gifs.gif', | |
id: 'catgif' | |
}); | |
var catgifTimer = 20; | |
var player; | |
var videotime = 0; | |
var fps = 1000 / 24; | |
var spinvideo = false; | |
var videoRotate = 0; | |
function onYouTubeIframeAPIReady() { | |
player = new YT.Player('player', { | |
events: { | |
'onReady': onPlayerReady, | |
} | |
}); | |
} | |
function onPlayerReady(event) { | |
function updateTime() { | |
var oldTime = videotime; | |
if(player && player.getCurrentTime) { | |
videotime = player.getCurrentTime(); | |
} | |
if(videotime !== oldTime) { | |
onCue(videotime); | |
} | |
if (spinvideo) { | |
videoRotate += 2; | |
$(player.f).css('transform', 'rotate('+videoRotate+'deg)'); | |
} | |
} | |
timeupdater = setInterval(updateTime, fps); | |
} | |
function onCue(currentTime) { | |
if (currentTime > currentSubtitle * subtitleInterval) { | |
$subtitles.text(subtitles[currentSubtitle]); | |
if (currentSubtitle < subtitles.length) currentSubtitle++; | |
} | |
if (currentTime > currentBackground * backgroundInterval) { | |
$body.css('background-color', backgroundColors[currentBackground%2]); | |
currentBackground++; | |
} | |
if (currentTime > catgifTimer) $('#container').append($catgif); | |
} | |
$('#play').on('click', function() { | |
player.playVideo(); | |
}); | |
$('#seek').on('click', function() { | |
player.seekTo(100); | |
}); | |
$('#spin').on('click', function() { | |
spinvideo = !spinvideo; | |
}); | |
$('#jump').on('click', function() { | |
if (player && player.getCurrentTime) | |
player.seekTo(player.getCurrentTime()+10); | |
}); | |
$('#stop').on('click', function() { | |
player.stopVideo(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment