Last active
November 18, 2016 10:18
-
-
Save maheshwaghmare/a838fdfeddcb94704a3517fc8ebc7c40 to your computer and use it in GitHub Desktop.
YouTube player JS API Reference for iframe embeds
This file contains 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
/** | |
* YouTube <iframe> video | |
* | |
* Set 40% volume for YouTube <iframe> video | |
*/ | |
var DebugLog = false, // For debugging | |
YouTubeID = 'YOUTUBE_IFRAME_ID', // Set YouTube <iframe> id | |
YouTubeVolume = 40; // Set volume from 1 to 100 | |
// Debug Log | |
if( DebugLog ) { | |
console.log( 'YouTubeID: ' + YouTubeID ); | |
} | |
// Debug Log | |
/** | |
* 2. This code loads the IFrame Player API code asynchronously. | |
*/ | |
var tag = document.createElement('script'); | |
tag.src = "https://www.youtube.com/iframe_api"; | |
var firstScriptTag = document.getElementsByTagName('script')[0]; | |
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); | |
/** | |
* 3. This function creates an <iframe> (and YouTube player) | |
* after the API code downloads. | |
*/ | |
var player; | |
function onYouTubeIframeAPIReady() { | |
// Debug Log | |
if( DebugLog ) { | |
console.log( 'Called onYouTubeIframeAPIReady()' ); | |
} | |
// Debug Log | |
player = new YT.Player(YouTubeID, { | |
events: { | |
'onReady': onPlayerReady, | |
'onStateChange': onPlayerStateChange | |
} | |
}); | |
} | |
/** | |
* 4. The API will call this function when the video player is ready. | |
*/ | |
function onPlayerReady(event) { | |
// Debug Log | |
if( DebugLog ) { | |
console.log( 'Called onPlayerReady()' ); | |
console.log( 'event.target: ' + JSON.stringify( event.target ) ); | |
} | |
// Debug Log | |
event.target.setVolume( YouTubeVolume ); | |
// event.target.playVideo(); | |
} | |
/** | |
* 5. The API calls this function when the player's state changes. | |
* The function indicates that when playing a video (state=1), | |
* the player should play for six seconds and then stop. | |
*/ | |
var done = false; | |
function onPlayerStateChange(event) { | |
// Debug Log | |
if( DebugLog ) { | |
console.log( 'Called onPlayerStateChange()' ); | |
} | |
// Debug Log | |
/** Stop Video after 6000 ms */ | |
// if (event.data == YT.PlayerState.PLAYING && !done) { | |
// setTimeout(stopVideo, 6000); | |
// done = true; | |
// } | |
} | |
/** | |
* 6. Stop video | |
*/ | |
function stopVideo() { | |
// Debug Log | |
if( DebugLog ) { | |
console.log( 'Called onPlayerStateChange()' ); | |
} | |
// Debug Log | |
player.stopVideo(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment