Little Known Way to Create a Fully Customizable ActionScript 3.0 YouTube Player

So you want to integrate YouTube videos in your Flash application and think that the YouTube API will get you there. If you’re doing ActionScript 3.0 development, it won’t. However, in this post and a bunch of follow-ups, I’ll show you how it is possible to get that video playing. See TheCouchTV, the random YouTube player, for an example. Jut click on the video to make it go full screen.

The first thing you’ll notice if you go to Google’s API site, is that everything is for JavaScript and ActionScript 2.0. No problem you’ll say, I don’t feel like learning AS2, but I do know my way around JavaScript. That’s all fine, until you want to play that video fullscreen. Due to security constraints, it is not possible to fullscreen a Flash applet from outside the applet (pretty reasonable if you ask me). So you need to add a button inside Flash, but the fully customizable and chromeless YouTube player is AS2, so it cannot be easily integrated in an AS3 application.

It is possible, and it will be the first thing you’ll find when you start Googling for solutions. There are a bunch of wrappers that can make it work, but they don’t feel “right”. It’s messy, especially if you like to be in full control. If you look even further, most likely, you’ll end up on Shane McCartney’s excellent Flash blog, which has a nice Flex application showing you how to directly access the YouTube FLV files. No need for the YouTube supplied Flash applet. The code is available, it’s just not very well documented. The AS3 sample underneath the player won’t even work, because Shane changed the API afterwards.

Stairs to Home
Creative Commons License photo credit: Ivy Dawned

This series of posts will show you the key features of the YouTube interface Shane created and it will begin to expand on it. As the Flex GUI components are not available to FlashDevelop users, I won’t go into those. But I will give you some info to directly stream it using standard Flash objects, no need for external libraries. I’ll just use the API to get a list of videos, pick a random one and start playing it. These are the steps needed to get it work. I’ve split them up to not make the posts too long:

  • Getting a list of videos (and some project setup) [in this post]
  • A bit about how the Flash stage works and fullscreen
  • Install a php script to get the randomly generated key [later post]
  • Getting the key for a video [later post]
  • playing the video using Flash’s FLV player classes [later post]

Before we start, lets configure a FlashDevelop project

  • Make sure you use the latest version, FlashDevelop (FD) is improving with every release, even a minor one. I’m using 3.0.0 Beta9 for this post.
  • Create a new AS3 project in a directory of your choice.
  • FD will create a directory structure. “bin” are the files you’ll upload to the webserver when everything is done. “src” holds your ActionScript files and “lib” everything else (like images)
  • Download Shane’s youTube.zip file with his YouTube library and extract it.
  • Copy the “com” directory in “currentas3classes” into your own “src” directory. (Don’t overwrite Main.as, we can’t use it, because it uses Flex classes not available freely)
  • FlashDevelop should notice this automatically and add the “com” directory structure to your project.
  • Open the Main.as in your project (FD created a base layout for you)
  • Ready to go.

First things first. Before you can start developing and running your YouTube applications, you should get your own developer key. This is a really painless procedure, it will take you less then two minutes, even less if you already have a Google account (who hasn’t?). When you have this key, open the YouTube.as file in com/flashdynamix/services. On line 14 you’ll see the variable that you need to change (it’s a public variable, so you could do it in the main, but I think it’s better to do it here)

public static var clientKey : String = "ytapi-XXXXXXXX-YYYYYYYYY-vuj2k916-0";

With that little thing out of the way, it’s time to discover the YouTube.as class. This is the central class you will be using to access all data on YouTube. This class works asynchronuously. You launch a method (for instance videosForTag) and it will just return nothing. In the background the class sends a request to YouTube and when the response is received, it will generate an event.

The main program should then be listening to that event and it can read and process the result at that point. It will be much clearer with a little code. I added a YouTube private variable and two listeners, the init method is than really short and clean:

package
{
	import com.flashdynamix.events.CustomEvent;
	import com.flashdynamix.services.YouTube;
	import flash.display.Sprite;
	import flash.events.ErrorEvent;
	import flash.events.Event;

	public class Main extends Sprite
	{

		private var yt : YouTube;

		public function Main():void
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}

		private function init(e:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			yt = new YouTube();
			yt.addEventListener(Event.COMPLETE, onLoaded);
			yt.addEventListener(ErrorEvent.ERROR, onError);
			yt.videosForTag("lego");
		}

		private function onLoaded(e:CustomEvent):void {
			switch (e.id) {
				case YouTube.SEARCH :
					trace("search finished");
					try {
						for each (var video:Object in e.value.items) {
							trace(video.title + " - " + video.link);
						}
					} catch (evt:ArgumentError) {
						trace("ERROR : No Videos For Tag");
					}
					break;
			}
		}

		private function onError(e:ErrorEvent):void {
			trace("IOError : " + e );
		}

	}

}

So what happens when you run the program:

  1. When the object is initialized, the init method is called.
  2. The init method instantiates a YouTube object and attaches 2 event listeners. One for when an error is encountered during a request and one for when the request is completed.
  3. As a last step, the method videosForTag is invoked. This will send a request to YouTube and get the first 20 movies that match the “Lego” tag.
  4. If an error occurs (for instance, no Internet connection), the onError method called to display the error.
  5. If no error occurs, the onLoaded method is called and it will print out the title and url for each of the 20 movies that were found.

That’s pretty much all there is to it. Depending on which method you call on the YouTube object, it will return a CustomEvent with a different id. If you want to experiment, add a default option that traces the id and you’re on your way.

In this post we saw the YouTube class and how it can be used to asynchronuously connect to the YouTube API to get lists of videos. The next step is going to be to actually play one of those movies. If you can’t wait, go ahead and check out the rest of Shane’s code, that’s the way I learned it. It’s really not that hard.