Playing YouTube Videos In Flash Using ActionScript 3.0

By Blue_Chi | Flash CS5 | ActionScript 3.0 | Intermediate

This tutorial will teach you how to play a YouTube directly inside your Flash movie without having to navigate to the YouTube website. This is possible to do by using the YouTube API provided by Google for developers to their own websites and applications on top of YouTube.

The example below shows a YouTube video loaded inside a Flash movie with a custom play and pause button.

Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

This tutorial will teach you how to load a YouTube video in your Flash movie to create a similar effect.

This is an intermediate level tutorial that requires you to know the basics of AS3 Variables, functions, event handling, and Loader Class. The actual manipulation of the YouTube video would be carried out through the custom methods of the YouTube API which we will go through in this tutorial.

Loading the YouTube API - No Component Necessary

Unlike the Google Maps ActionScript 3.0 API, the YouTube AS3 API doesn't require you to download and install a special component for you to be able to play YouTube videos inside your project, instead you directly load a special YouTube file during runtime using the Loader Class and then use that file to play any video you want. You can view the official documentation for the YouTube AS3 API on this page.

The basic process outline for loading the API and using it is as following:

  1. Configure Domain Security to allow YouTube to communicate with our movie.
  2. Create a variable to hold a reference to our YouTube player.
  3. Use the Loader Class to load the YouTube API file
  4. Create event handlers to control the player once the API file has successfully loaded and got initiated.
  5. Order the player to play the specific YouTube video we wish to see.

We are going to go through these step one at a time.

Starting Off and Configuring Security

So to start off, simply create a new Flash Movie in AS3 format, right-click the only frame you have on the timeline and select Actions to open up the Actions Panel, all of our code will be placed here.

In order to allow the YouTube object to interact with our movie, we will have to configure the security settings of our movie to allow communication with the YouTube website, to do this you simply type the following:

Security.allowDomain("www.youtube.com");

This step is necessary to allow the file which we will load from the YouTube website to run ActionScript code on the SWF file that will be hosted on our server. You do not need to learn much about security in order to use the YouTube API other than that you need to use the code above.

Player Variable

We cannot load a YouTube video directly into a Flash movie, instead we have to load a special SWF file that has the codes to create the YouTube player window and all other components necessary to run the video (along with the advertisements Google displays over the video) and then ask this SWF file to play the video we need by using the API methods published by Google.

The first thing to do is create a variable for our player, we are going to get the actual reference to this player later after we load the SWF file, so in the mean time use the var keyword to create a variable called my_player. We are going to use the type of the variable as a generic Object as we do not have access to any of the information of the YouTube API before we load the file:.

Security.allowDomain("www.youtube.com");

var my_player:Object;
You can learn more about AS3 Variables and Data Types by reading our tutorial on this topic.


The variable my_player will be used later to refer to the player object once it is loaded. We are going to load the external player SWF file next

Loading the Player Object Using the Loader Class

We are going to use the Loader Class to load our YouTube player along with its API from the YouTube servers as an SWF file, as with the regular use of the Loader Class, we need to start off by creating an instance of the class, We will call it my_loader, and then we will instantly load the player object by using the .load() method:

Security.allowDomain("www.youtube.com");

var my_player:Object;

var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));

You can learn more about the AS3 Loader Class by reviewing our tutorial on this topic.

We got the reference to the URL of the YouTube API from the official Google documentation.

In order to work with the player object we need to wait for it to be fully initialized and then pass commands to it. To do that we will first have to register our instance of the Loader Class with an event listener function:

Security.allowDomain("www.youtube.com");

var my_player:Object;

var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
my_loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
You can learn more about AS3 Event Handling by reviewing our tutorial on this topic.

Our onLoaderInit() function will be triggered once our YouTube API file has been initialized and ready for our to communicate with it. The first thing that our function will do is to add my_loader to the Display List so that the YouTube video appears on the screen when you ask to have one played, create your event listener function below your existing code and do that:

Security.allowDomain("www.youtube.com");

var my_player:Object;

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

function onLoaderInit(e:Event):void{
addChild(my_loader);
}

The second task to do is to store a reference for the contents of our loaded file in the my_player variable we created earlier so that we can easily refer to the player object later in the project.

Security.allowDomain("www.youtube.com");

var my_player:Object;

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

function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
}

Even though our API file is initialized, we must further wait for it be "ready" before we can ask it to play a specific YouTube video. Google has created custom events which we can listen to and trigger actions through them, we will register our my_player object with a special onReady event that will trigger a function we will create later to deal with the player when it is finally ready.

Security.allowDomain("www.youtube.com");

var my_player:Object;

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

function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
my_player.addEventListener("onReady", onPlayerReady);
}
Check the official YouTube API documentation to learn about all the available custom events.

Configuring the Player When It's Ready

At this stage our player is ready, the basic configuration that we will do is to set its size, and then tell it to play a specific movie. That could be done by using the setSize() method and loadVideoByID() methods. The setSize() method is pretty self explanatory, all you have to do is provide the width and height your desire your played to be in pixels and it will work. We are going to create the onPlayerReady() function and ask it to do that:

Security.allowDomain("www.youtube.com");

var my_player:Object;

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

function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
my_player.addEventListener("onReady", onPlayerReady);
}

function onPlayerReady(e:Event):void{
my_player.setSize(640,360);
}

The final step in loading the video would be to use the loadVideoById()which requires you to provide the ID of the video, the starting at which you want the video to play, and the quality at which the video should be played. It is used in the following format:

sampleYouTubePlayer.loadVideoById(myVideoID, startingPoint);

The ID of the video is the string at the end of a YouTube URL. For example, in this URL:

http://www.youtube.com/watch?v=_OBlgSz8sSM

The ID of the video is _OBlgSz8sSM. It is always the value that follows the v= part. The starting point value doesn't require much explanation other than its a value in seconds.

So lets play a YouTube video on our player:

Security.allowDomain("www.youtube.com");

var my_player:Object;

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

function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
my_player.addEventListener("onReady", onPlayerReady);
}

function onPlayerReady(e:Event):void{
my_player.setSize(640,360);
my_player.loadVideoById("_OBlgSz8sSM",0);
}

You can test your movie at this stage to see your movie of choice played in your Flash project!

Customizing the Player

We have showed you the very basic functionality of the YouTube API, the API also provides a number of additional methods to control the player. Namely, the following functions are available:

  • loadVideoById() - This method loads a video and play it instantly once the video is ready to be played.
  • cueVideoById() - This method loads a video, but does not play it automatically. The use will have to use the playVideo() method to play
  • playVideo() - Plays a cued video or a paused video.
  • pauseVideo() - Pauses a video at its current position.
  • stopVideo() - Stops the video and resets it to the beginning.
  • mute() - Mutes the sound of the video.
  • unMute() - Unmutes the sound of the video.

All of these methods can be called only after the player is ready. You can read the whole list of available methods and properties at the official documentation page.

In order to create a player and pause button similar to the ones showed in our example above you will have to place two buttons on the stage and then assign the instance names play_btn and pause_btn then use the code below:

Security.allowDomain("www.youtube.com");

var my_player:Object;

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

function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
my_player.addEventListener("onReady", onPlayerReady);
}

function onPlayerReady(e:Event):void{
my_player.setSize(640,360);
my_player.cueVideoById("_OBlgSz8sSM",0);
}

play_btn.addEventListener(MouseEvent.CLICK, playVid);
function playVid(e:MouseEvent):void {
my_player.playVideo();
}
pause_btn.addEventListener(MouseEvent.CLICK, pauseVid);
function pauseVid(e:MouseEvent):void {
my_player.pauseVideo();
}

This concludes our tutorial, I hope that you learnt something new about using the YouTube API in Flash. If you have any questions or comments please feel free to post at the Republic of Code Forum.

- End of Tutorial