This document provides reference information for the YouTube ActionScript 2.0 player API.
Note: The ActionScript 2.0 Player API was officially deprecated on October 14, 2009. Per the YouTube API deprecation policy, detailed in our Terms of Service, we will continue to operate the ActionScript 2.0 API for a period of three years (until October 14, 2012). You should use the ActionScript 3.0 Player API for any new applications. We also recommend that you migrate existing applications that use the ActionScript 2.0 Player API to use the ActionScript 3.0 Player API instead. |
Contents
Overview
The ActionScript 2.0 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. 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 8 or higher installed to view everything correctly.
To allow room for critical player functionality, players must be at least 200px by 200px.
Note: YouTube does not support running the AS2 player under Flash Lite.
Getting Started
To add the embedded player for a specific video into your Flash file, you will be loading the following SWF into a MovieClip:
http://youtube.googleapis.com/v/VIDEO_ID?version=2
Alternatively, you may wish to load the chromeless player into your MovieClip if you are building your own custom controls in Flash:
http://youtube.googleapis.com/apiplayer?version=2
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 Flash file. You can also customize your users' experience by using player parameters to control various types of player behavior.
Operations
The ActionScript 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 subsections that follow list the functions that the player API supports.
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()
orseekTo()
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 whenplayVideo()
is called. If you specify astartSeconds
value and then callseekTo()
, then the player plays from the time specified in theseekTo()
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 thesetPlaybackQuality
function for more information about playback quality.
- The required
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 thesetPlaybackQuality
function for more information about playback quality.
- The required
player.cueVideoByUrl(mediaContentUrl: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()
orseekTo()
is called.- The
mediaContentUrl
must be a fully qualified YouTube player URL in the formathttp://www.youtube.com/v/VIDEO_ID
. In YouTube Data API video feeds, theurl
attribute of the<media:content>
tag contains a fully qualified player URL when the tag'sformat
attribute has a value of5
. startSeconds
accepts a float/integer and specifies the time from which the video should start playing whenplayVideo()
is called. If you specifystartSeconds
and then callseekTo()
, then the player plays from the time specified in theseekTo()
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 thesetPlaybackQuality
function for more information about playback quality.
- The
player.loadVideoByUrl(mediaContentUrl:String, startSeconds:Number, suggestedQuality:String):Void
- Loads and plays the specified video.
- The
mediaContentUrl
must be a fully qualified YouTube player URL in the formathttp://www.youtube.com/v/VIDEO_ID
. In YouTube Data API video feeds, theurl
attribute of the<media:content>
tag contains a fully qualified player URL when the tag'sformat
attribute has a value of5
. startSeconds
accepts a float/integer and specifies the time from which the video should start playing. IfstartSeconds
(number can be a float) is 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 thesetPlaybackQuality
function for more information about playback quality.
- The
player.playVideo():Void
- Plays the currently cued/loaded video. The final player state after this function executes will be
playing
(1).
Note: YouTube only counts playbacks that are initiated through a native play button in either the embedded or chromeless 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 theended
(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 thepaused
(2) state, thestopVideo
function could put the player into any not-playing state, includingended
(0),paused
(2),video cued
(5) orunstarted
(-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'sNetStream
object. (See Adobe's documentation for more information.) -
The
allowSeekAhead
parameter determines whether the player will make a new request to the server if theseconds
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 totrue
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.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. 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. 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.
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 or an approximation of the video's size.
Specifically, this function will approximate the total size of the video when the value ofplayer.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():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.
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 arehighres
,hd1080
,hd720
,large
,medium
andsmall
. 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 thesetPlaybackQuality
function.
ThesuggestedQuality
parameter value can besmall
,medium
,large
,hd720
,hd1080
,highres
ordefault
. We recommend that you set the parameter value todefault
, 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, ahd720
quality video will actually look better than anhd1080
quality video. We recommend calling thegetAvailableQualityLevels()
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 thesuggestedQuality
parameter value todefault
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 thecueVideoById
,loadVideoById
orsetPlaybackQuality
functions.
If you call thesetPlaybackQuality
function with asuggestedQuality
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 oflarge
, and that is unavailable, then the playback quality will be set tomedium
(as long as that quality level is available).
In addition, settingsuggestedQuality
to a value that is not a recognized quality level is equivalent to settingsuggestedQuality
todefault
. - Quality level
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 arehighres
,hd1080
,hd720
,large
,medium
andsmall
. 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. 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, thegetDuration()
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.
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. Thelistener
is a reference to the function that will execute when the specified event fires.
Queueing functions
Queueing functions for videos
Playback controls and player settings
Playing a video
Changing the player volume
Setting the player size
Playback status
Playback quality
Retrieving video information
Adding an event listener
Special Functions
The ActionScript specific API calls are listed below:
player.isPlayerLoaded():Boolean
- Returns true when the player SWF is loaded, initialized, and ready to receive API calls. It will return false or could be undefined before the player is completely loaded and initialized.
player.destroy():Void
- Destroys the player instance. This method should be called before unloading the player SWF from your parent SWF.
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 thesetPlaybackQuality(suggestedQuality)
function is called. Similarly, your code should not assume that playback quality will only change as a result of an explicit call tosetPlaybackQuality
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", "hd720", "hd1080", and "highres".
onError
- This event is fired when an error in the player occurs. The possible error codes are
2
,100
,101
, and150
:- The
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. - 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 as101
, it's just101
in disguise!
- The
Examples
Loading the player SWF
Because of the architecture of the player SWF, using ActionScript's built in MovieClipLoader will not give you accurate information. To detect when the player SWF is ready to receive API calls, you should call player.isPlayerLoaded()
, which will return true when the player is completely loaded and initialized.
At this point, you may subscribe to events and make any other API calls to the player.
In this example, we wait for the player SWF to load using MovieClipLoader's onLoadInit
event, and then start an interval to check for when the player SWF is initialized.
Using the player SWF in Adobe Flash
This is the easiest way to get started if you have Adobe Flash installed. Just open the FLA and publish the SWF. The code can be seen in the "Actions - Frame" tab.
Using the player SWF using MTASC
If you don't have Flash installed you can compile a simple AS2 file that includes the player. This can then be compiled with an ActionScript compiler like MTASC.
To compile the above AS2 source file into a SWF, use the following MTASC command:
path/to/mtasc -swf ytdemo.swf -main -header 800:600:20 YTDemo.as
Once the player is loaded and ready, all API calls can be made in the same way as the JavaScript API.
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. }
Working with AS3
Please refer to the instructions for using ActionScript 3.0 for more information.
Caveats
When unloading a YouTube player, you should always call
destroy()
first. This will close the NetStream object and stop the
video from continuing to download even after the player has been unloaded. It
will also remove references to the player SWF so if you load a new player SWF
into your application, the new SWF can load and initialize properly.
You should only call destroy()
on the player. There is no need to call removeMovieClip()
.