)
This document provides reference information for the YouTube JavaScript player API.
The JavaScript API allows users to control the YouTube chromeless or embedded video players via JavaScript. Calls can be made to play, pause, seek to a certain time in a video, set the volume, mute the player, and other useful functions.
The end user must have Flash Player 8 or higher installed to view everything correctly. Because of this requirement, we suggest using SWFObject to embed the SWF and detect the user's Flash Player version.
In addition, any HTML page that contains the YouTube player must implement a JavaScript function named onYouTubePlayerReady. The API will call this function when the player is fully loaded and the API is ready to receive calls. See the Event Handlers section for more details.
Note: To test any of these calls, you must have your file running on a webserver, as the Flash player restricts calls between local files and the internet.
You can enable the JavaScript API handlers for chromeless and embedded players. To enable the JavaScript API for a player, add the URL parameter enablejsapi=1 to the player's URL.
Enabling the JavaScript API for a chromeless player
If your application is using a chromeless player, use the following URL to load the player in your application and enable JavaScript API handlers in the player. You can then build your own custom player controls using JavaScript:
http://www.youtube.com/apiplayer?enablejsapi=1&version;=3
Enabling the JavaScript API for an embedded player
Use the following URL to load an embedded video player. In the URL, replace the string VIDEO_ID with the 11-character YouTube video ID that identifies the video that the player will show.
http://www.youtube.com/e/VIDEO_ID?version=3&enablejsapi=1
When the player is ready, the API will call the onYouTubePlayerReady callback function. You can use the optional playerapiid parameter to the player URL to pass a value, such as the player ID, back to the callback function.
http://www.youtube.com/e/VIDEO_ID?enablejsapi=1&version=3&playerapiid=ytplayer
Once the player SWF is loaded, you can use the queueing functions – cueVideoById(), loadVideoById(), cueVideoByUrl(), loadVideoByUrl(), cuePlaylist(), or loadPlaylist() – to load a particular YouTube video or playlist.
The Player API demo lets you compare the chromeless and embedded video players, and the examples below provide more detailed information about how to embed a YouTube player SWF into your page. You can also customize your users' experience by using player parameters to control various types of player behavior.
In order to call the player API methods, you must first get a reference to the player object you wish to control. This can be done by calling getElementById() on the object or embed tag containing the player SWF if using SWFObject to embed the player SWF.
player.cueVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):VoidplayVideo() or seekTo() is called.
videoId parameter specifies the YouTube Video ID of the video to be played. In YouTube Data API video feeds, the <yt:videoid> tag specifies the ID.startSeconds parameter accepts a float/integer and specifies the time from which the video should start playing when playVideo() is called. If you specify a startSeconds value and then call seekTo(), then the player plays from the time specified in the seekTo() call. When the video is cued and ready to play, the player will broadcast a video cued event (5).suggestedQuality parameter specifies the suggested playback quality for the video. Please see the definition of the setPlaybackQuality function for more information about playback quality.player.loadVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):VoidvideoId parameter specifies the YouTube Video ID of the video to be played. In YouTube Data API video feeds, the <yt:videoid> tag specifies the ID.startSeconds parameter accepts a float/integer. If it is specified, then the video will start from the closest keyframe to the specified time.suggestedQuality parameter specifies the suggested playback quality for the video. Please see the definition of the setPlaybackQuality function for more information about playback quality.player.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number):VoidplayVideo() or seekTo() is called.
mediaContentUrl must be a fully qualified YouTube player URL in the format http://www.youtube.com/e/VIDEO_ID. In YouTube Data API video feeds, the url attribute of the <media:content> tag contains a fully qualified player URL when the tag's format attribute has a value of 5.startSeconds accepts a float/integer and specifies the time from which the video should start playing when playVideo() is called. If you specify startSeconds and then call seekTo(), then the player plays from the time specified in the seekTo() call. When the video is cued and ready to play, the player will broadcast a video cued event (5).player.loadVideoByUrl(mediaContentUrl:String, startSeconds:Number):VoidmediaContentUrl must be a fully qualified YouTube player URL in the format http://www.youtube.com/e/VIDEO_ID. In YouTube Data API video feeds, the url attribute of the <media:content> tag contains a fully qualified player URL when the tag's format attribute has a value of 5.startSeconds accepts a float/integer and specifies the time from which the video should start playing. If startSeconds (number can be a float) is specified, the video will start from the closest keyframe to the specified time.player.cuePlaylist(playlist:String|Array, index:Number, startSeconds:Number, suggestedQuality:String):Void5).
The required playlist parameter specifies either a YouTube playlist ID or an array of YouTube video IDs. In YouTube Data API feeds, the <yt:playlistid> tag specifies a playlist ID, and the <yt:videoid> tag specifies a video ID.
The optional index parameter specifies the index of the first video in the playlist that will play. The parameter uses a zero-based index, and the default parameter value is 0, so the default behavior is to load and play the first video in the playlist.
The optional startSeconds parameter accepts a float/integer and specifies the time from which the first video in the playlist should start playing when the playVideo() function is called. If you specify a startSeconds value and then call seekTo(), then the player plays from the time specified in the seekTo() call. If you cue a playlist and then call the playVideoAt() function, the player will start playing at the beginning of the specified video.
The optional suggestedQuality parameter specifies the suggested playback quality for the video. Please see the definition of the setPlaybackQuality function for more information about playback quality.
player.loadPlaylist(playlist:String|Array, index:Number, startSeconds:Number, suggestedQuality:String):VoidThe required playlist parameter specifies either a YouTube playlist ID or an array of YouTube video IDs. In YouTube Data API feeds, the <yt:playlistid> tag specifies a playlist ID, and the <yt:videoid> tag specifies a video ID.
The optional index parameter specifies the index of the first video in the playlist that will play. The parameter uses a zero-based index, and the default parameter value is 0, so the default behavior is to load and play the first video in the playlist.
The optional startSeconds parameter accepts a float/integer and specifies the time from which the first video in the playlist should start playing.
The optional suggestedQuality parameter specifies the suggested playback quality for the video. Please see the definition of the setPlaybackQuality function for more information about playback quality.
player.playVideo():Voidplaying (1).player.pauseVideo():Voidpaused (2) unless the player is in the ended (0) state when the function is called, in which case the player state will not change.player.stopVideo():VoidstopVideo first.paused (2) state, the stopVideo function could put the player into any not-playing state, including ended (0), paused (2), video cued (5) or unstarted (-1).player.seekTo(seconds:Number, allowSeekAhead:Boolean):Voidseconds parameter identifies the time from which the video should start playing.
seek() method of the Flash player's NetStream object. In practice, this means that the player could advance to a keyframe just before or just after the specified time. (For more information, see Adobe's documentation for the NetStream class.)allowSeekAhead parameter determines whether the player will make a new request to the server if the seconds parameter specifies a time outside of the currently buffered video data. We recommend that you set this parameter to false while the user is dragging the mouse along a video progress bar and then set the parameter to true when the user releases the mouse.playing (1) unless the value of the seconds parameter is greater than the video length, in which case the final player state will be ended (0).player.clearVideo():VoidstopVideo(). Note that this function has been deprecated in the ActionScript 3.0 Player API.player.nextVideo():VoidIf player.nextVideo() is called while the last video in the playlist is being watched, and the playlist is set to play continuously (loop), then the player will load and play the first video in the list.
If player.nextVideo() is called while the last video in the playlist is being watched, and the playlist is not set to play continuously, then playback will end.
player.previousVideo():VoidIf player.previousVideo() is called while the first video in the playlist is being watched, and the playlist is set to play continuously (loop), then the player will load and play the last video in the list.
If player.previousVideo() is called while the first video in the playlist is being watched, and the playlist is not set to play continuously, then the player will restart the first playlist video from the beginning.
player.playVideoAt(index:Number):VoidThe required index parameter specifies the index of the video that you want to play in the playlist. The parameter uses a zero-based index, so a value of 0 identifies the first video in the list. If you have shuffled the playlist, this function will play the video at the specified position in the shuffled playlist.
player.mute():Voidplayer.unMute():Voidplayer.isMuted():Booleanplayer.setVolume(volume:Number):Voidplayer.getVolume():NumbergetVolume() will return the volume even if the player is muted.player.setSize(width:Number, height:Number):Voidplayer.setLoop(loopPlaylists:Boolean):VoidThis function indicates whether the video player should continuously play a playlist or if it should stop playing after the last video in the playlist ends. The default behavior is that playlists do not loop.
This setting will persist even if you load or cue a different playlist, which means that if you load a playlist, call the setLoop function with a value of true, and then load a second playlist, the second playlist will also loop.
The required loopPlaylists parameter identifies the looping behavior.
If the parameter value is true, then the video player will continuously play playlists. After playing the last video in a playlist, the video player will go back to the beginning of the playlist and play it again.
If the parameter value is false, then playbacks will end after the video player plays the last video in a playlist.
player.setShuffle(shufflePlaylist:Boolean):VoidThis function indicates whether a playlist's videos should be shuffled so that they play back in an order different from the one that the playlist creator designated. If you shuffle a playlist after it has already started playing, the list will be reordered while the video that is playing continues to play. The next video that plays will then be selected based on the reordered list.
This setting will not persist if you load or cue a different playlist, which means that if you load a playlist, call the setShuffle function, and then load a second playlist, the second playlist will not be shuffled.
The required shufflePlaylist parameter indicates whether YouTube should shuffle the playlist.
If the parameter value is true, then YouTube will shuffle the playlist order. If you instruct the function to shuffle a playlist that has already been shuffled, YouTube will shuffle the order again.
If the parameter value is false, then YouTube will change the playlist order back to its original order.
player.getVideoBytesLoaded():Numberplayer.getVideoBytesTotal():Numberplayer.getVideoStartBytes() is greater than zero. The function needs to approximate the video's size because the video's actual size is only communicated to the player when the video starts from the beginning.player.getVideoStartBytes():Numberplayer.getPlayerState():Numberplayer.getCurrentTime():Numberplayer.getPlaybackQuality():Stringundefined if there is no current video. Possible return values are highres, hd1080, hd720, large, medium and small.player.setPlaybackQuality(suggestedQuality:String):VoidonPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function.suggestedQuality parameter value can be small, medium, large, hd720, hd1080, highres or default. We recommend that you set the parameter value to default, which instructs YouTube to select the most appropriate playback quality, which will vary for different users, videos, systems and other playback conditions.hd720 quality video will actually look better than an hd1080 quality video. We recommend calling the getAvailableQualityLevels() function to determine which quality levels are available for a video.suggestedQuality parameter value to default to enable YouTube to select the most appropriate playback quality.small: Player height is 240px, and player dimensions are at least 320px by 240px for 4:3 aspect ratio.medium: Player height is 360px, and player dimensions are 640px by 360px (for 16:9 aspect ratio) or 480px by 360px (for 4:3 aspect ratio).large: Player height is 480px, and player dimensions are 853px by 480px (for 16:9 aspect ratio) or 640px by 480px (for 4:3 aspect ratio).hd720: Player height is 720px, and player dimensions are 1280px by 720px (for 16:9 aspect ratio) or 960px by 720px (for 4:3 aspect ratio).hd1080: Player height is 1080px, and player dimensions are 1920px by 1080px (for 16:9 aspect ratio) or 1440px by 1080px (for 4:3 aspect ratio).highres: Player height is greater than 1080px, which means that the player's aspect ratio is greater than 1920px by 1080px.default: YouTube selects the appropriate playback quality. This setting effectively reverts the quality level to the default state and nullifies any previous efforts to set playback quality using the cueVideoById, loadVideoById or setPlaybackQuality functions.setPlaybackQuality function with a suggestedQuality level that is not available for the video, then the quality will be set to the next lowest level that is available. For example, if you request a quality level of large, and that is unavailable, then the playback quality will be set to medium (as long as that quality level is available).suggestedQuality to a value that is not a recognized quality level is equivalent to setting suggestedQuality to default.player.getAvailableQualityLevels():Arrayhighres, hd1080, hd720, large, medium and small. This function returns an empty array if there is no current video.player.getDuration():NumbergetDuration() will return 0 until the video's metadata is loaded, which normally happens just after the video starts playing.player.getVideoUrl():Stringplayer.getVideoEmbedCode():Stringplayer.getPlaylist():ArraysetShuffle function to shuffle the playlist order, then the getPlaylist() function's return value will reflect the shuffled order.player.getPlaylistIndex():NumberIf you have not shuffled the playlist, the return value will identify the position where the playlist creator placed the video. The return value uses a zero-based index, so a value of 0 identifies the first video in the playlist.
If you have shuffled the playlist, the return value will identify the video's order within the shuffled playlist.
Adding an event listener
player.addEventListener(event:String, listener:String):Voidevent. The Events section below identifies the different events that the player might fire. The listener is a string that specifies the function that will execute when the specified event fires.onStateChangeonPlaybackQualityChangesetPlaybackQuality(suggestedQuality) function, this event will fire if the playback quality actually changes. Your code should respond to the event and should not assume that the quality will automatically change when the setPlaybackQuality(suggestedQuality) function is called. Similarly, your code should not assume that playback quality will only change as a result of an explicit call to setPlaybackQuality or any other function that allows you to set a suggested playback quality.onError2, 100, 101, and 150:2 error code is broadcast when a request contains an invalid parameter. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.100 error code is broadcast when the video requested is not found. This occurs when a video has been removed (for any reason), or it has been marked as private.101 error code is broadcast when the video requested does not allow playback in the embedded players.150 is the same as 101, it's just 101 in disguise!Your HTML pages that display the chromeless player must implement a callback function named onYouTubePlayerReady. The API will call this function when the player is fully loaded and the API is ready to receive calls.
onYouTubePlayerReady(playerid)playerapiid is passed into the player via URL arguments, then it will be passed to this function.We recommend using SWFObject to embed any players that will be accessed using the JavaScript API. This will allow you to detect the end user's Flash Player version (the JavaScript API requires Flash Player 8 or higher), and also will get rid of the 'Click to activate this control' box when using Internet Explorer to view the player.
To enabled the API in the SWF, you must pass in the parameter enablejsapi=1.
See below for an example of using the script to embed a YouTube player with the JavaScript API enabled, and with a playerapiid of ytplayer.
<script type="text/javascript" src="swfobject.js"></script>
<div id="ytapiplayer">
You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script type="text/javascript">
var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/e/VIDEO_ID?enablejsapi=1&playerapiid=ytplayer",
"ytapiplayer", "425", "356", "8", null, null, params, atts);
</script>
The allowScriptAccess parameter in the code is needed to allow the player SWF to call functions on the containing HTML page, since the player is hosted on a different domain from the HTML page.
The only attribute we're passing in is the id of the embed object — in this case, myytplayer. This id is what we'll use to get a reference to the player using getElementById().
swfobject.embedSWF will load the player from YouTube and embed it onto your page.
swfobject.embedSWF(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj)
swfUrlStr - This is the URL of the SWF. Note that we have appended the enablejsapi and playerapiid parameters to the normal YouTube SWF URL to enable JavaScript API calls.replaceElemIdStr - This is the HTML DIV id to replace with the embed content. In the example above, it is ytapiplayer.widthStr - Width of the player.
heightStr - Height of the player.
swfVersionStr - The minimum required version for the user to see the content. In this case, version 8 or above is needed. If the user does not have 8 or above, they will see the default line of text in the HTML DIV.
xiSwfUrlStr - (Optional) Specifies the URL of your express install SWF. Not used in this example.
flashVarsObj - (Optional) Specifies your FlashVars in name:value pairs. Not used in this example.
parObj - (Optional) The parameters for the embed object. In this case, we've set allowScriptAccess.
AttObj - (Optional) The attributes for the embed object. In this case, we've set the id to myytplayer.
See the SWFObject documentation for further explanation.
Once the player is ready, it wil call onYouTubePlayerReady.
To get the reference to the player, use getElementById(). Once you have the object, you can start making calls to the API.
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
}
You can now call functions using the player reference. For example, if you wanted to play the video when a user clicked a link, it would look like this:
function play() {
if (ytplayer) {
ytplayer.playVideo();
}
}
<a href="javascript:void(0);" onclick="play();">Play</a>
Or simply,
<a href="javascript:ytplayer.playVideo()">Play</a>
Subscribe to events by adding an event listener to the player reference. For example, to get notified when the player's state changes, add an event listener for onStateChange and include a callback function.
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}
function onytplayerStateChange(newState) {
alert("Player's new state: " + newState);
}
You can use the YouTube Player Demo to test the features of the JavaScript API with either the embedded or chromeless player. In addition, the Google Code Playground lets you debug and run JavaScript Player API code to see how your code would appear to a web user.
This update contains the following changes:
The following API functions have been added to support playlist players:
The cuePlaylist function loads the thumbnail image for the first video in the specified playlist and prepares the player to play the playlist. However, the player does not request the video until your application calls either the playVideo, playVideoAt, or seekTo function.
The loadPlaylist function loads and plays the specified playlist.
The getPlaylist function plays the currently cued playlist. The final player state after this function executes will be playing (1).
The getPlaylistIndex function returns the position in which the current video appears in the playlist. The first video will have a position of 1, the second video will have a position of 2, and so forth.
The nextVideo function instructs the player to load and play the next video in the playlist.
The previousVideo function instructs the player to load and play the previous video in the playlist.
The playVideoAt function instructs the player to load and play a specific video in the playlist.
The setLoop function lets you dynamically instruct the player to continuously play the playlist or, alternately, to sto playing after the playlist has played all of the videos in the playlist.
The setShuffle function instructs YouTube to play the videos in the playlist in random order (or to play them in their designated order.
This update contains the following changes:
The definition of the playVideo function has been updated to note that YouTube only counts playbacks that are initiated through a native play button in either the embedded or chromeless player.
If you link to the Player Parameters document from either the link in the Getting started section or from this paragraph, the page will initially only display parameters supported in the AS3 player. You can use the pulldown menu in the Overview section of that document to see parameters supported in other players (HTML5 or AS2) or all parameters.