YouTube

YouTube ActionScript 3.0 Player API Reference

This document provides reference information for the YouTube ActionScript 3.0 (AS3) player API.

Contents

  1. Overview
  2. Requirements
  3. Getting started
  4. Operations
    1. Functions
      1. Queueing functions
      2. Playback controls and player settings
      3. Playback status
      4. Playback quality
      5. Retrieving video information
      6. Retrieving playlist information
      7. Adding an event listener
    2. Special functions
    3. Events
  5. Examples
    1. Loading the player SWF
    2. Determining the state of a quality toggle button
    3. Standalone sample code
  6. Revision history

Overview

The AS3 API allows users to control the YouTube video players by loading the player into a Flash application and making calls via ActionScript to the player's public API. Your application can use a chromeless player, for which you will build custom controls in Flash, or an embedded player that has built-in controls. 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 ActionScript API is automatically activated when the player is loaded into another SWF.

Requirements

The end user must have Flash Player 10.1 or higher installed to view everything correctly.

Embedded players must have a viewport that is at least 200px by 200px. If the player displays controls, it must be large enough to fully display the controls without shrinking the viewport below the minimum size. We recommend 16:9 players be at least 480 pixels wide and 270 pixels tall.

Getting started

You can use a chromeless player or an embedded player in your application. Both players support the same functions. However, the embedded player displays standard controls, including a play/pause button, a progress bar, a volume control, and more. The chromeless player, on the other hand, does not display any controls, so you will need to develop your own custom player controls in Flash. You can also customize your users' experience by using player parameters to control various types of player behavior.

  • Loading the chromeless player

    If your application is using a chromeless player, use the following URL to load the player in your application:

    http://www.youtube.com/apiplayer?version=3
  • Loading the 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/v/VIDEO_ID?version=3

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 Flash file. Once the player SWF is loaded, you can use the queueing functionscueVideoById, loadVideoById, cueVideoByUrl, loadVideoByUrl, cuePlaylist, and loadPlaylist – to load a particular YouTube video or playlist.

Enabling JavaScript API handlers

You can also enable JavaScript API handlers for your player by adding the URL parameter enablejsapi=1 to the player's URL.

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

Please see the JavaScript Player API documentation for more information.

Operations

The AS3 API is very similar to the JavaScript API, with some small changes to how the player is initialized and some additional functions. For examples of how to initialize and make calls to the player via ActionScript, see the examples below.

Functions

The following subsections list the functions that the player API supports.

Queueing functions

Queueing functions allow you to load and play a video, a playlist, or another list of videos. If you are using the object syntax, described below, to call these functions, you can also queue or load a list of search results or a user's list of uploaded videos.

The API supports two different syntaxes for calling the queueing functions.

  • The argument syntax requires function arguments to be listed in a prescribed order.

  • The object syntax lets you pass an object as a single parameter and to define object properties for the function arguments that you wish to set. In addition, the API may support additional functionality that the argument syntax does not support.

For example, the loadVideoById function can be called in either of the following ways. Note that the object syntax supports the endSeconds property, which the argument syntax does not support.

  • Argument syntax

    loadVideoById("bHQqvYy5KYo", 5, "large")
  • Object syntax

    loadVideoById({'videoId': 'bHQqvYy5KYo', 'startSeconds': 5, 'endSeconds': 60, 'suggestedQuality': 'large'});

The different queueing functions for videos and playlists are described below.

Queueing functions for videos

cueVideoById

  • Argument syntax

    player.cueVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):Void

  • Object syntax

    player.cueVideoById({videoId:String, startSeconds:Number, endSeconds:Number, suggestedQuality:String}):Void

This function 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 endSeconds parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop playing when playVideo() is called. If you specify an endSeconds value and then call seekTo(), the endSeconds value will no longer be in effect.
  • 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.

loadVideoById

  • Argument syntax

    player.loadVideoById(videoId:String, startSeconds:Number, suggestedQuality:String):Void

  • Object syntax

    player.loadVideoById({videoId:String, startSeconds:Number, endSeconds:Number, suggestedQuality:String}):Void

This function 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 endSeconds parameter accepts a float/integer. If it is specified, then the video will stop playing at 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.

cueVideoByUrl

  • Argument syntax

    player.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number, suggestedQuality:String):Void

  • Object syntax

    player.cueVideoByUrl({mediaContentUrl:String, startSeconds:Number, endSeconds:Number, suggestedQuality:String}):Void

This function 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 mediaContentUrl parameter specifies a fully qualified YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID?version=3. In YouTube Data API video feeds, the <media:content> tag's url attribute contains a fully qualified player URL when the tag's format attribute has a value of 5.
  • 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 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).
  • The optional endSeconds parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop playing when playVideo() is called. If you specify an endSeconds value and then call seekTo(), the endSeconds value will no longer be in effect.
  • 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.

loadVideoByUrl

  • Argument syntax

    player.loadVideoByUrl(mediaContentUrl:String, startSeconds:Number, suggestedQuality:String):Void

  • Object syntax

    player.loadVideoByUrl({mediaContentUrl:String, startSeconds:Number, endSeconds:Number, suggestedQuality:String}):Void

This function loads and plays the specified video.

  • The required mediaContentUrl parameter specifies a fully qualified YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID?version=3. 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.
  • The optional startSeconds parameter 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.
  • The optional endSeconds parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop 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.

Queueing functions for lists

The cuePlaylist and loadPlaylist functions allow you to load and play a playlist or list of videos. If you are using the object syntax to call these functions, you can also queue (or load) a list of search results or a user's list of uploaded videos.

Since the functions work differently depending on whether they are called using the argument syntax or the object syntax, both calling methods are documented below.

  • Argument syntax

    player.cuePlaylist(playlist:String|Array, index:Number, startSeconds:Number, suggestedQuality:String):Void
    Queues the specified playlist. When the playlist is cued and ready to play, the player will broadcast a video cued event (5).
    • The required playlist parameter specifies an array of YouTube video IDs. In YouTube Data API feeds, 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):Void
    This function loads the specified playlist and plays it.
    • The required playlist parameter specifies an array of YouTube video IDs. In YouTube Data API feeds, 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.

  • Object syntax

    player.cuePlaylist({listType:String,
                        list:String,
                        index:Number,
                        startSeconds:Number,
                        suggestedQuality:String}):Void
    Queues the specified list of videos. The list can be a playlist, a search results feed, or a user's uploaded videos feed. When the list is cued and ready to play, the player will broadcast a video cued event (5).
    • The optional listType property specifies the type of results feed that you are retrieving. Valid values are playlist, search, and user_uploads. The default value is playlist.

    • The required list property contains a key that identifies the particular list of videos that YouTube should return.

      • If the listType property value is playlist, then the list property specifies the playlist ID or an array of video IDs. In YouTube Data API feeds, the <yt:playlistid> tag specifies a playlist ID, and the <yt:videoid> tag specifies a video ID.
      • If the listType property value is search, then the list property specifies the search query.
      • If the listType property value is user_uploads, then the list property identifies the user whose uploaded videos will be returned.

    • The optional index property specifies the index of the first video in the list 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 list.

    • The optional startSeconds property accepts a float/integer and specifies the time from which the first video in the list 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 list and then call the playVideoAt() function, the player will start playing at the beginning of the specified video.

    • The optional suggestedQuality property specifies the suggested playback quality for the list's videos. Please see the definition of the setPlaybackQuality function for more information about playback quality.

    player.loadPlaylist({list:String,
                         listType:String,
                         index:Number,
                         startSeconds:Number,
                         suggestedQuality:String}):Void
    This function loads the specified list and plays it. The list can be a playlist, a search results feed, or a user's uploaded videos feed.
    • The optional listType property specifies the type of results feed that you are retrieving. Valid values are playlist, search, and user_uploads. The default value is playlist.

    • The required list property contains a key that identifies the particular list of videos that YouTube should return.

      • If the listType property value is playlist, then the list property specifies a playlist ID or an array of video IDs. In YouTube Data API feeds, the <yt:playlistid> tag specifies a playlist ID, and the <yt:videoid> tag specifies a video ID.
      • If the listType property value is search, then the list property specifies the search query.
      • If the listType property value is user_uploads, then the list property identifies the user whose uploaded videos will be returned.

    • The optional index property specifies the index of the first video in the list 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 list.

    • The optional startSeconds property accepts a float/integer and specifies the time from which the first video in the list should start playing.

    • The optional suggestedQuality property specifies the suggested playback quality for the list's videos. Please see the definition of the setPlaybackQuality function for more information about playback quality.

Playback controls and player settings

Playing a video

player.playVideo():Void
Plays the currently cued/loaded video. The final player state after this function executes will be playing (1).

Note: A playback only counts toward a video's official view count if it is initiated via a native play button in the player.
player.pauseVideo():Void
Pauses the currently playing video. The final player state after this function executes will be paused (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():Void
Stops and cancels loading of the current video. This function should be reserved for rare situations when you know that the user will not be watching additional video in the player. If your intent is to pause the video, you should just call the pauseVideo function. If you want to change the video that the player is playing, you can call one of the queueing functions without calling stopVideo first.

Important: Unlike the pauseVideo function, which leaves the player in the 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):Void
Seeks to a specified time in the video. If the player is paused when the function is called, it will remain paused. If the function is called from another state (playing, video cued, etc.), the player will play the video.
  • The seconds parameter identifies the time to which the player should advance.

    The player will advance to the closest keyframe before that time unless the player has already downloaded the portion of the video to which the user is seeking. In that case, the player will advance to the closest keyframe before or after the specified time as dictated by the seek() method of the Flash player's NetStream object. (See Adobe's documentation for more information.)

  • The 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 drags the mouse along a video progress bar and then set it to true when the user releases the mouse. This approach lets a user scroll to different points of a video without requesting new video streams by scrolling past unbuffered points in the video. When the user releases the mouse button, the player advances to the desired point in the video and requests a new video stream if necessary.

player.getClickToPlayButton(videoId:string, startSeconds:Number, suggestedQuality:String):DisplayObject
Creates and returns a thumbnail that functions as a click-to-play button for a video. The button is an extension of the player that issued it, and when the button is clicked, the player will play the associated video. This function, which is only supported in the Flash (AS3) Player API, provides the best way to trigger a video playback when a user clicks on a video thumbnail.

  • The required videoId parameter identifies the video associated with the new button. The button is skinned with the video's hqdefault thumbnail image. Since the button displays the video's thumbnail image, the application does not need to retrieve the video thumbnail image URLs using the YouTube Data API.

  • The optional startSeconds parameter accepts a float/integer and specifies the time from which the video should start playing when the button is clicked. If specified, 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.

The code snippet below shows a function that creates an array of click-to-play buttons for a given player and set of video IDs. Each button is a Flash DisplayObject that the application can resize, stylize, and display as appropriate.

function createFeaturedButtons(player:Object, featuredVideos:Array) {
  var results:Array = [];
  for each (var id:String in featuredVideos) {
    results.push(player.getClickToPlayButton(id));
  }
  return results;
}

Playing a video in a playlist

player.nextVideo():Void
This function loads and plays the next video in the playlist.
  • If 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():Void
This function loads and plays the previous video in the playlist.
  • If 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):Void
This function loads and plays the specified video in the playlist.
  • The 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.

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. This method should be used instead of setting the width and height properties of the MovieClip. Note that this method does not constrain the proportions of the video player, so you will need to maintain a 4:3 aspect ratio. The default size of the chromeless SWF when loaded into another SWF is 320px by 240px and the default size of the embedded player SWF is 480px by 385px.

Setting the playback rate

player.getPlaybackRate():Number
This function retrieves the playback rate of the currently playing video. The default playback rate is 1, which indicates that the video is playing at normal speed. Playback rates may include values like 0.25, 0.5, 1, 1.5, and 2.
player.setPlaybackRate(suggestedRate:Number):Void
This function sets the suggested playback rate for the current video. If the playback rate changes, it will only change for the video that is already cued or being played. If you set the playback rate for a cued video, that rate will still be in effect when the playVideo function is called or the user initiates playback directly through the player controls. In addition, calling functions to cue or load videos or playlists (cueVideoById, loadVideoById, etc.) will reset the playback rate to 1.

Calling this function does not guarantee that the playback rate will actually change. However, if the playback rate does change, the onPlaybackRateChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackRate function.

The getAvailablePlaybackRates method will return the possible playback rates for the currently playing video. However, if you set the suggestedRate parameter to a non-supported integer or float value, the player will round that value down to the nearest supported value in the direction of 1.

Note: Even though the AS3 player supports playback rate controls, variable speeds are currently only supported in the HTML5 player.

player.getAvailablePlaybackRates():Array
This function returns the set of playback rates in which the current video is available. The default value is 1, which indicates that the video is playing in normal speed.

The function returns an array of numbers ordered from slowest to fastest playback speed. Even if the player does not support variable playback speeds, the array should always contain at least one value (1).

Setting playback behavior for playlists

player.setLoop(loopPlaylists:Boolean):Void

This 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):Void

This 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.

Playback status

player.getVideoLoadedFraction():Float
Returns a number between 0 and 1 that specifies the percentage of the video that the player shows as buffered. This method returns a more reliable number than the now-deprecated getVideoBytesLoaded and getVideoBytesTotal methods.
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.
player.getVideoStartBytes():Number
Deprecated as of October 31, 2012. Returns the number of bytes the video file started loading from. (This method now always returns a value of 0.) 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.getVideoBytesLoaded():Number
Deprecated as of July 18, 2012. Instead, use the getVideoLoadedFraction method to determine the percentage of the video that has buffered.

Returns the number of bytes loaded for the current video.
player.getVideoBytesTotal():Number
Deprecated as of July 18, 2012. Instead, use the getVideoLoadedFraction method to determine the percentage of the video that has buffered.

Returns the size in bytes of the currently loaded/playing video or an approximation of the video's size.

Specifically, this function will approximate the total size of the video when the value of player.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.

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 highres, hd1080, 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. However, if the playback quality does change, 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, 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.

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 1280px by 720px video player, a 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.

The list below shows the playback quality levels that correspond to different standard player sizes. We recommend that you set the height of your video player to one of the values listed below and that you size your player to use 16:9 aspect ratio. As stated above, even if you choose a standard player size, we also recommend that you set the suggestedQuality parameter value to default to enable YouTube to select the most appropriate playback quality.

  • Quality level small: Player height is 240px, and player dimensions are at least 320px by 240px for 4:3 aspect ratio.
  • Quality level 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).
  • Quality level 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).
  • Quality level 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).
  • Quality level 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).
  • Quality level highres: Player height is greater than 1080px, which means that the player's aspect ratio is greater than 1920px by 1080px.
  • 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 highres, hd1080, 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.

If the currently playing video is a live event, the getDuration() function will return the elapsed time since the live video stream began. Specifically, this is the amount of time that the video has streamed without being reset or interrupted. In addition, this duration is commonly longer than the actual event time since streaming may begin before the event's start time.
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.

Retrieving playlist information

player.getPlaylist():Array
This function returns an array of the video IDs in the playlist as they are currently ordered. By default, this function will return video IDs in the order designated by the playlist owner. However, if you have called the setShuffle function to shuffle the playlist order, then the getPlaylist() function's return value will reflect the shuffled order.
player.getPlaylistIndex():Number
This function returns the index of the playlist video that is currently playing.
  • If 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:Function):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 reference to the function that will execute when the specified event fires.

Special functions

The ActionScript specific API calls are listed below:

player.destroy():Void
This function destroys the player instance. It should be called before unloading the player SWF from your parent SWF.

Important: You should always call player.destroy() to unload a YouTube player. This function will close the NetStream object and stop additional videos from downloading after the player has been unloaded. If your code contains additional references to the player SWF, you also need to destroy those references separately when you unload the player.

Events

onReady
This event is fired when the player is loaded and initialized, meaning it is ready to receive API calls.
onStateChange
This event fires whenever the player's state changes. The value that the API passes to your event listener function will specify an integer that corresponds to the new player state. Possible values are:

  • -1 (unstarted)
  • 0 (ended)
  • 1 (playing)
  • 2 (paused)
  • 3 (buffering)
  • 5 (video cued).

When the player first loads a video, it will broadcast an unstarted (-1) event. When a video is cued and ready to play, the player will broadcast a video cued (5) event. In your code, you can specify the integer values or you can use one of the following namespaced variables:

  • YT.PlayerState.ENDED
  • YT.PlayerState.PLAYING
  • YT.PlayerState.PAUSED
  • YT.PlayerState.BUFFERING
  • YT.PlayerState.CUED

onPlaybackQualityChange
This event fires 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 application 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 API passes to the event listener function will be a string that identifies the new playback quality. Possible values are:

  • small
  • medium
  • large
  • hd720
  • hd1080
  • highres

onPlaybackRateChange
This event fires whenever the video playback rate changes. For example, if you call the setPlaybackRate(suggestedRate) function, this event will fire if the playback rate actually changes. Your application should respond to the event and should not assume that the playback rate will automatically change when the setPlaybackRate(suggestedRate) function is called. Similarly, your code should not assume that the video playback rate will only change as a result of an explicit call to setPlaybackRate.

The value that the API passes to the event listener function will be a number that identifies the new playback rate. The getAvailablePlaybackRates method returns a list of the valid playback rates for the currently cued or playing video.

Note: Even though the AS3 player supports this event, variable speeds are currently only supported in the HTML5 player.

onError
This event fires if an error occurs in the player. The value that the API passes to the event listener function will be an integer that identifies the type of error that occurred. Possible values are:

  • 2 – The request contains an invalid parameter value. 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 – The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.
  • 101 – The owner of the requested video does not allow it to be played in embedded players.
  • 150 – This error is the same as 101. It's just a 101 error in disguise!
onApiChange
This event is fired to indicate that the player has loaded (or unloaded) a module with exposed API methods. Your application can listen for this event and then poll the player to determine which options are exposed for the recently loaded module. Your application can then retrieve or update the existing settings for those options.

The following command retrieves an array of module names for which you can set player options:
player.getOptions();
Currently, the only module that you can set options for is the cc module, which handles closed captioning in the player. Upon receiving an onApiChange event, your application can use the following command to determine which options can be set for the cc module:
player.getOptions('cc');
By polling the player with this command, you can confirm that the options you want to access are, indeed, accessible. The following commands retrieve and update module options:
Retrieving an option:
player.getOption(module, option);

Setting an option
player.setOption(module, option, value);
The table below lists the options that the API supports:

Module Option Description
cc fontSize This option adjusts the font size of the captions displayed in the player.

Valid values are -1, 0, 1, 2, and 3. The default size is 0, and the smallest size is -1. Setting this option to an integer below -1 will cause the smallest caption size to display, while setting this option to an integer above 3 will cause the largest caption size to display.
cc reload This option reloads the closed caption data for the video that is playing. The value will be null if you retrieve the option's value. Set the value to true to reload the closed caption data.

Examples

Loading the player SWF

The AS3 API uses a different initialization sequence than the AS2 player. Whereas the AS2 player uses the isPlayerLoaded() function to determine when the player is loaded, initialized and ready to receive API calls, the AS3 player uses a more robust event system. The sample code below demonstrates how to load and initialize the AS3 API player:

// The player SWF file on www.youtube.com needs to communicate with your host
// SWF file. Your code must call Security.allowDomain() to allow this
// communication.
Security.allowDomain("www.youtube.com");

// This will hold the API player instance once it is initialized.
var player:Object;

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));

function onLoaderInit(event:Event):void {
    addChild(loader);
    loader.content.addEventListener("onReady", onPlayerReady);
    loader.content.addEventListener("onError", onPlayerError);
    loader.content.addEventListener("onStateChange", onPlayerStateChange);
    loader.content.addEventListener("onPlaybackQualityChange", 
        onVideoPlaybackQualityChange);
}

function onPlayerReady(event:Event):void {
    // Event.data contains the event parameter, which is the Player API ID 
    trace("player ready:", Object(event).data);

    // Once this event has been dispatched by the player, we can use
    // cueVideoById, loadVideoById, cueVideoByUrl and loadVideoByUrl
    // to load a particular YouTube video.
    player = loader.content;
    // Set appropriate player dimensions for your application
    player.setSize(480, 360);
}

function onPlayerError(event:Event):void {
    // Event.data contains the event parameter, which is the error code
    trace("player error:", Object(event).data);
}

function onPlayerStateChange(event:Event):void {
    // Event.data contains the event parameter, which is the new player state
    trace("player state:", Object(event).data);
}

function onVideoPlaybackQualityChange(event:Event):void {
    // Event.data contains the event parameter, which is the new video quality
    trace("video quality:", Object(event).data);
}

Determining the state of a quality toggle button

The sample code below demonstrates how YouTube determines the status of its quality toggle button, which lets users select a different playback quality based on available quality levels for a video.

var qualityLevels:Array = getAvailableQualityLevels()
// qualityLevels may be undefined if the API function does not exist, 
// in which case this conditional is false
if (qualityLevels.length > 1) {

    var highestQuality:String = qualityLevels[0]
    if (highestQuality begins with "hd") {
        // Brand quality toggle button as HD.
    } else {
        // Brand quality toggle button as HQ.
        // The highest available quality is shown, but it is not HD video.
    }

    var quality:String = getPlaybackQuality();
    if (quality == 'small' || quality == 'medium') {
        // The user is not watching the highest quality available 
        // can can toggle to a higher quality.
    } else {
        // The user is watching the highest quality available 
        // and can toggle to a lower quality.
    }

} else {
    // Hide the toggle button because there is no current video or
    // there is only one quality available.
}

Standalone sample code

Standalone sample code illustrating basic ActionScript 3.0 Player API usage is available as part of the gdata-samples Google Code project. After checking out the code from the source code repository, you'll find the sample in the ytplayer/actionscript3/com/google/youtube/examples/ directory. The code uses the Flex UI libraries, and can be built with the open source Flex SDK.

The ActionScript 2.0 Player API has been officially deprecated. However, there are still samples available on the documentation page.

Revision history

This section lists YouTube Flash (AS3) Player API changes and documentation updates. Subscribe to this changelog. Subscribe

March 25, 2014

This update contains the following changes:

  • The Requirements section has been updated to note that embedded players must have a viewport that is at least 200px by 200px. If a player displays controls, it must be large enough to fully display the controls without shrinking the viewport below the minimum size. We recommend 16:9 players be at least 480 pixels wide and 270 pixels tall.

October 31, 2012

This update contains the following changes:

  • The Queueing functions section has been updated to better explain the option of using either argument syntax or object syntax to call any of those functions. Note that the API may support additional functionality in object syntax that the argument syntax does not support.

    In addition, the descriptions and examples for each of the video queueing functions have been updated to reflect the newly added support for object syntax. (The documentation already provided examples for calling the playlist queueing functions using object syntax.)

  • When called using object syntax, each of the video queueing functions supports an endSeconds property, which accepts a float/integer and specifies the time when the video should stop playing when playVideo() is called.

  • The getVideoStartBytes method has been deprecated. The method now always returns a value of 0.

August 6, 2012

This update contains the following changes:

  • The new getClickToPlayButton function creates and returns a video thumbnail that, when clicked, causes the source player to play that video. This function is only available in the Flash (AS3) Player API.

    We recommend that you use this function in Flash (AS3) applications to generate video thumbnail images that serve as click-to-play buttons.

  • The API supports several new functions and one new event that can be used to control the video playback speed. However, note that variable playback speeds are currently only supported in the HTML5 player.

    • Functions

      • getAvailablePlaybackRates – Retrieve the supported playback rates for the cued or playing video. Note that variable playback rates are currently only supported in the HTML5 player.
      • getPlaybackRate – Retrieve the playback rate for the cued or playing video.
      • setPlaybackRate – Set the playback rate for the cued or playing video.

    • Events

July 19, 2012

This update contains the following changes:

March 26, 2012

This update contains the following changes:

  • The Requirements section has been updated to note the minimum player size. Embedded players must have a viewport that is at least 200px by 200px. If the player displays controls, it must be large enough to fully display the controls without shrinking the viewport below the minimum size. We recommend 16:9 players be at least 480 pixels wide and 270 pixels tall.

December 5, 2011

This update contains the following changes:

  • The Requirements section has been updated to note that the end user must have Flash Player 10.1 or higher installed for the player to display everything correctly.

  • The definition of the seekTo function has been updated to indicate that if the player is paused when the function is called, the player will remain paused after the function executes.

November 17, 2011

This update contains the following changes:

  • The AS3 Player API now supports an object syntax for calling queueing functions. Those functions are cueVideoById, loadVideoById, cueVideoByUrl, loadVideoByUrl, cuePlaylist, and loadPlaylist.

    The object syntax lets you pass an object as the only argument to a function. The object's properties specify the function arguments that you wish to set.

  • The cuePlaylist and loadPlaylist functions both support additional functionality when called using the object syntax. Specifically, when using the object syntax, you can use both functions to retrieve either a playlist, a list of search results, or a list of a user's uploaded videos. If you are using the argument syntax, you can only retrieve a playlist.

    To support this functionality, the object syntax defines a listType property that can be used to specify whether the player is retrieving a playlist, a list of search results, or a list of a user's uploaded videos. The object's list property then specifies the playlist ID, search query, or username that identifies the desired feed.

    To properly reflect this functionality, the Queueing functions for playlists section has been renamed to Queueing functions for lists. Within that section, the cuePlaylist and loadPlaylist functions are each defined twice to explain how to call each function using either the argument syntax or the object syntax.

  • The definitions of the cueVideoByUrl and loadVideoByUrl functions have been updated in two ways:

      The definition of the mediaContentUrl argument for each function has been updated to note that the value must specify the version parameter. As such, the argument's value must be a fully qualified YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID?version=3.

    • Both functions support a suggestedQuality parameter. This parameter specifies the suggested playback quality for the video.
  • The definition of the getDuration function has been updated to explain that if the currently playing video is a live event, the function will return the elapsed time since the video stream began.

July 29, 2011

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.

February 17, 2011

This update contains the following changes:

  • If you link to the Player Parameters document from this document, the page will now display parameters supported in any version of the player. You can use the pulldown menu in the Overview section of that document to only see parameters supported in the AS3 player (or in the HTML5 or AS2) players.

February 3, 2011

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.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.