My favorites | English | Sign in

Sign up for Google I/O 2010 today!

YouTube APIs and Tools

YouTube logo

YouTube JavaScript Player API Reference

This document provides reference information for the YouTube JavaScript player API.

Contents

Overview

The JavaScript API allows users to control the YouTube 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.

Requirements

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.

Getting Started

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.

To enable the JavaScript API, you must pass the URL parameter enablejsapi=1 in the URL of the player you wish to control. For example, you'd want to use the following URL to embed the SWF.

http://www.youtube.com/v/VIDEO_ID?enablejsapi=1

This enables the JavaScript API handlers in the player, and also tells the player to alert the containing HTML page via a callback when the player is loaded and ready to receive JavaScript calls. When the player is ready, the JavaScript function onYouTubePlayerReady will be called.

You may optionally pass in a playerapiid parameter, which will identify the player when the onYouTubePlayerReady callback is invoked. Whatever value is passed in as playerapiid will be passed back to onYouTubePlayerReady as the first argument.

http://www.youtube.com/v/VIDEO_ID?enablejsapi=1&playerapiid=ytplayer

Alternatively, you may wish to load the chromeless player into your page if you are building your own custom controls using JavaScript:

http://www.youtube.com/apiplayer?enablejsapi=1

You can request the AS3 chromeless player by adding the &version=3 parameter to the above URL:

http://www.youtube.com/apiplayer?enablejsapi=1&version=3

Once the chromeless player SWF has been loaded, you can use cueVideoById(), loadVideoById(), cueVideoByUrl() or loadVideoByUrl() to load a particular YouTube video.

See the examples below for more detailed information about how to embed a YouTube player SWF into your page.

Operations

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.

Functions

Queueing functions

player.cueVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):Void
Loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until playVideo() or seekTo() is called.
  • The required 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.
  • The optional 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).
  • 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.loadVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):Void
Loads and plays the specified video.
  • The required 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.
  • The optional startSeconds parameter accepts a float/integer. If it is specified, then the video will start from the closest keyframe to the specified time.
  • 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.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void
Loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until playVideo() or seekTo() is called.
  • The mediaContentUrl must be a fully qualified YouTube player URL in the format http://www.youtube.com/v/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):Void
Loads and plays the specified video.
  • The mediaContentUrl must be a fully qualified YouTube player URL in the format http://www.youtube.com/v/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.

Playback controls and player settings

Playing a video

player.playVideo():Void
Plays the currently cued/loaded video.
player.pauseVideo():Void
Pauses the currently playing video.
player.stopVideo():Void
Stops the current video. This function also cancels the loading of the video.
player.seekTo(seconds:Number, allowSeekAhead:Boolean):Void
Seeks to the specified time of the video in seconds. The seekTo() function will look for the closest keyframe before the seconds specified. This means that sometimes the play head may seek to just before the requested time, usually no more than ~2 seconds.

The allowSeekAhead parameter determines whether or not the player will make a new request to the server if seconds is beyond the currently loaded video data.
player.clearVideo():Void
Clears the video display. This function is useful if you want to clear the video remnant after calling stopVideo(). Note that this function has been deprecated in the ActionScript 3.0 Player API.

Changing the player volume

player.mute():Void
Mutes the player.
player.unMute():Void
Unmutes the player.
player.isMuted():Boolean
Returns true if the player is muted, false if not.
player.setVolume(volume:Number):Void
Sets the volume. Accepts an integer between 0 and 100.
player.getVolume():Number
Returns the player's current volume, an integer between 0 and 100. Note that getVolume() will return the volume even if the player is muted.

Setting the player size

player.setSize(width:Number, height:Number):Void
Sets the size in pixels of the player. You should not have to use this method in JavaScript as the player will automatically resize when the containing elements in the embed code have their height and width properties modified.

Playback status

player.getVideoBytesLoaded():Number
Returns the number of bytes loaded for the current video.
player.getVideoBytesTotal():Number
Returns the size in bytes of the currently loaded/playing video.
player.getVideoStartBytes():Number
Returns the number of bytes the video file started loading from. Example scenario: the user seeks ahead to a point that hasn't loaded yet, and the player makes a new request to play a segment of the video that hasn't loaded yet.
player.getPlayerState():Number
Returns the state of the player. Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
player.getCurrentTime():Number
Returns the elapsed time in seconds since the video started playing.

Playback quality

player.getPlaybackQuality():String
This function retrieves the actual video quality of the current video. It returns undefined if there is no current video. Possible return values are hd720, large, medium and small.
player.setPlaybackQuality(suggestedQuality:String):Void
This function sets the suggested video quality for the current video. The function causes the video to reload at its current position in the new quality. If the playback quality does change, it will only change for the video being played.

Calling this function does not guarantee that the playback quality will actually change. If the playback quality does change, it will only change for the video being played. At that time, the onPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function.

The suggestedQuality parameter value can be small, medium, large, hd720 or default. Setting the parameter value to default instructs YouTube to select the most appropriate playback quality, which will vary for different users, videos, systems and other playback conditions.

When you suggest a playback quality for a video, the suggested quality will only be in effect for that video. You should select a playback quality that corresponds to the size of your video player. For example, if your page displays a 640px by 360px video player, a medium quality video will actually look better than a large quality video. The following list shows recommended playback quality levels for different player sizes:

  • Quality level small: Player resolution less than 640px by 360px.
  • Quality level medium: Minimum player resolution of 640px by 360px.
  • Quality level large: Minimum player resolution of 854px by 480px.
  • Quality level hd720: Minimum player resolution of 1280px by 720px.
  • Quality level 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.

If you call the 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).

In addition, setting suggestedQuality to a value that is not a recognized quality level is equivalent to setting suggestedQuality to default.
player.getAvailableQualityLevels():Array
This function returns the set of quality formats in which the current video is available. You could use this function to determine whether the video is available in a higher quality than the user is viewing, and your player could display a button or other element to let the user adjust the quality.

The function returns an array of strings ordered from highest to lowest quality. Possible array element values are hd720, large, medium and small. This function returns an empty array if there is no current video.

Your client should not automatically switch to use the highest (or lowest) quality video or to any unknown format name. YouTube could expand the list of quality levels to include formats that may not be appropriate in your player context. Similarly, YouTube could remove quality options that would be detrimental to the user experience. By ensuring that your client only switches to known, available formats, you can ensure that your client's performance will not be affected by either the introduction of new quality levels or the removal of quality levels that are not appropriate for your player context.

Retrieving video information

player.getDuration():Number
Returns the duration in seconds of the currently playing video. Note that getDuration() will return 0 until the video's metadata is loaded, which normally happens just after the video starts playing.
player.getVideoUrl():String
Returns the YouTube.com URL for the currently loaded/playing video.
player.getVideoEmbedCode():String
Returns the embed code for the currently loaded/playing video.

Adding an event listener

player.addEventListener(event:String, listener:String):Void
Adds a listener function for the specified event. 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.

Events

onStateChange
This event is fired whenever the player's state changes. Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). When the SWF is first loaded it will broadcast an unstarted (-1) event. When the video is cued and ready to play it will broadcast a video cued event (5).
onPlaybackQualityChange
This event is fired whenever the video playback quality changes. For example, if you call the setPlaybackQuality(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.

The value that the event broadcasts is the new playback quality. Possible values are "small", "medium", "large" and "hd720".
onError
This event is fired when an error in the player occurs. The possible error codes are 100, 101, and 150. The 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. The 101 error code is broadcast when the video requested does not allow playback in the embedded players. The error code 150 is the same as 101, it's just 101 in disguise!

Event Handlers

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)
Called when the player is fully loaded and the API is ready to receive calls. If a playerapiid is passed into the player via URL arguments, then it will be passed to this function.

Examples

Embedding the YouTube player using SWFObject

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/v/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.

Getting the Player Reference

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");
    }

Issuing Calls

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> 

Subscribing to Events

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);
}

Live Demo

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.

Back to top