1. Code
  2. Flash

Creating a YouTube Search and Play Gadget with PureMVC


Following my tutorials on PureMVC and the YouTube Player API I thought it would be a good idea to show you how to use the YouTube GData API for searching for and playing videos. So I've created a little tutorial that combines your new PureMVC and YouTube Player skills into a nice and simple search and play gadget.

Before We Start...

This is a tutorial for intermediate to advanced Actionscripters and it would be handy if you first read my PureMVC and YouTube Player API tutorials.

Step 1: Why Use PureMVC?

You may be wondering why I've chosen to use PureMVC. Well, I think it's great! And it's a great tool that allows you to build something small and then expand it into a big application - it's all about scalability. So while we create this app, it's worth noting that this can be used as a gadget to be included in multiple places such as iGoogle, blogs and even gadget ads.

Step 2: The Set Up

Fire up your favourite IDE, whether it's Flex Builder, FDT, FlashDevelop or TextMate and create a new Actionscript project. We're also going to be creating a SWC so it's handy if you've got a copy of Flash (you can download a trail from Adobe's web site).

Additionally, we're going to be using GreenSock's TweenLite class and not forgetting the PureMVC codebase.

Note: In the the first few steps we're going to be setting up a skeleton for PureMVC. An explanation of the first steps is available on my PureMVC tutorial.

Step 3: Creating the Base App

Just like with any PureMVC app, we need to set up our base app. I'm going to start by just creating a simple background for the app and then running the start up command within the facade, so create a new file called "" within "src/":

Step 4: Creating the Facade

We now simply create the facade, nothing special, just like the facade we created in the PureMVC tutorial, so create a new file called "" inside "src/com/flashtuts/":

Step 5: Creating the Startup Command

Now we'll create our startup command and make sure that we register our proxy and application mediator. Create a file called "" in "src/com/flashtuts/controller/":

Step 6: Creating the Proxy

We now need to set up our proxy, so let's create a file called "" in "src/com/flashtuts/model/":

We'll be coming back to the proxy later in the tutorial as we'll be using it to load the data from GData and store it in the VO.

Step 7: Creating the VO

We're going to use the VO to store data from our GData query so that if the user searches for a keyword more than once, we'll just load the data from the VO rather than creating another request to the GData API. Create a file called "" in "src/com/flashtuts/model/vo/":

Have a quick read of the GData API documentation you'll see that the var "gdataURL" shows that we're going to get 15 results and we've left the URL open so that we can put the query string at the back of the request's URL.

Step 8: Creating the Application Mediator

The final part of our PureMVC skeleton is our application mediator. We'll create it and then get it to register our first view and mediator, the "ProgressView" and "ProgressViewMediator", so create a file called "" within "src/com/flashtuts/view/":

Step 9: Creating our Progress View

We'll simply start with a similar progress view to the one we made in the PureMVC tutorial, so create the file "" within "src/com/flashtuts/view/component/":

You'll notice that we're using a new class called "LoaderAsset". This, in fact, is a movie clip that we'll create in the Flash IDE and then use within our progress view instead of just showing a percentage.

Step 10: Creating the SWC

Fire up Flash IDE (if you haven't got the Flash IDE, you can download the trial from Adobe's web site) and create a new AS3 file:

Before we continue, we need to make sure Flash knows that we want to target Flash Player 9 and that we're exporting a SWC, so select 'Flash Player 9' from the drop down at the top and tick the box next to 'Export SWC' under the heading 'SWF Settings':

Now we'll create a simple loader. I've chosen to go for a spinning one, but it's up to you what you do. Create a circle and punch a hole in it:

Once you've put a hole in your circle, apply a radial gradient, move it to the right of the circle. Then copy half of the circle, paste it on top of the current circle and apply a solid fill to it. Done. Now, next thing is to make it rotate, so let's create a tween:

I've got my tween running for 15 frames, you can have yours fast, the same or slower. Now we simply set it to rotate once:

The last thing to do is wrap this all up in a movie clip. Once you've done that, open up the properties window for that movie clip and set it to export for Actionscript:

As you can see I've called it 'LoaderAsset', this linkage name will be the class name you'll use in your view, so back to our "ProgressView". Make sure you add your asset in the same way I have in the class:

Step 11: Setting up the Progress View Mediator

Our progress view mediator will be similar to the one we created in the PureMVC tutorial with the exception that there's no update as we just have a spinning wheel rather than a percentage sign. Create the file "" in "src/com/flashtuts/view/":

You're free to use whatever loader you want, but there's a problem with YouTube's GData. You see when Flash Player makes a call, most servers send the content-length of the request to the loader, thus allowing Flash Player to know how many bytes it's going to load and allowing us to work out a percentage. However, YouTube GData doesn't seem to send this content-length and whenever you try to work out a percentage, Flash Player finds itself dividing the 'bytesLoaded' with zero. Shame.

Step 12: Creating the Search View

Next thing we need to do is create our search view. This will contain a search box where the user will enter their query and then a button for them to press which runs the query. Additionally, we'll be using an event listener on the search box so that if the user were to hit 'enter' the query would still be run. Create a file called "" within "src/com/flashtuts/view/component/":

This code should be nothing new to an ActionScripter, but here's a quick run through: we first set the text format, then create the background box (I'm using Sprite.drawRoundRectComplex() to draw the box), I then set up the label, create the text input box and then import an asset from the SWC for the search button.

As I mentioned before, I've added an event listener to the text input box and to the submit button. This means that the user is able to hit enter or click on the submit button to run the query. The 'handleSearchFieldKeyUp()' function checks to make sure if the enter key has been hit, if it has, it then runs the search. This is also good practice for usability issues as people are often used to hitting enter rather than having to click a button.

Step 13: Creating the Search View Mediator

The search view mediator won't have too much there as it's not listening to any events, rather it's sending them to the facade. Start then, by creating a file called "" inside "src/com/flashtuts/view/":

If you look at the view, you'll notice that it'll dispatch a "DataEvent" up to the mediator. Within our mediator we listen to that and then send a notification to your facade. This notification will be picked up by a command which will interact with the proxy and then send an event with the results.

We've reached the stage when our view will be sending our query to the facade, so we now need to create a command to pass this query to our proxy and then update our proxy's code. It'll then run the query, store it in the VO, pass it back to a mediator and then the view.

Step 14: Creating the Data Command

We're going to start by updating the facade so that it will pass the notification "SearchView.SEARCH_RUN" to our data command. Open up "" and simply add another "registerCommand" within the facade's "initializeController()" function:

Now we need to create the "" file in "src/com/flashtuts/controller/":

This is quite a simple controller, it's listening in on one notification then just passing it to the proxy. Again, we reference the proxy using a get function, this means that we're using the facade's instance rather than re-declaring the proxy.

Step 15: Finishing the Proxy

Now that our view bubbles up the event to the facade and the facade passes it to our data command, we need our proxy to do the dirty work, so let's load some XML.

Unless you've worked with GData before, it's worth noting that the XML it passes back is in Atom format and it's got lots of namespaces within it. In AS2 using namespaces was a bit of a hack, as was the rest of the language, but now in AS3 there are two ways:

  1. The proper way
    This is the proper way but it's a pain in the bum as you need to declare each namespace in the AS3 before loading in the XML, like so:

    Only then can you access the XML's variables like so:

    So you see that you put the declared namespace and two colons (this :) in front of the tag's/attribute's name. This may look painful - and it is, but you can find out more on Adobe's LiveDocs.

  2. The easy way
    This way is much easier (and lazier I guess) but it gets the job done and isn't messy or a hack. A namespace is simply a method to associate tags (or attributes) to a URL reference, so for example GData references OpenSearch, YouTube's and Google's own schemas and more. The easy way around is instead of declaring namespaces and prefixing them to tag's/attribute's names, you simply add an asterisk (this *) like so:


So now we understand how to handle the XML we're getting back, let's go about finishing the proxy. Launch "" in "src/com/flashtuts/model/" and here's the code for it:

We start off with creating the public function that our data command will trigger "searchRun()". As you see it accepts one parameter, the query string:

Now to make the application run faster. I'm using the principle that once a query has been run, the data is stored in the VO and there's no need for that query to run again. So using AS3's Dictionary class, we're able to check to see if the results are already in the VO. If they're not, we need to get them, otherwise send them to our mediator. We'll come on to the "dataReady()" function a bit further down:

If the query hasn't yet been run, we need to load some XML:

You'll see that we're suffixing the query on to the 'gdataURL' string stored in our VO. We then reference the query string using the proxy's dictionary so that when data's ready, we can store it in the VO under that query and won't need to load it again. Then we add the event listeners and make the call. Once we've got the data back, we get the query from the dictionary, store it in the VO and then run the "dataReady()" function:

This function simply gets the entries and sends the notification back to the facade. Now we can display our videos.

Step 16: Creating the Results View

Once we have the entries, it's then easy for us to load the thumbnails for those entries and display them in a grid. Let's start by creating a file called "" inside "src/com/flashtuts/component/":

This is simply a class that just takes the YouTube video ids and then loads the corresponding thumbnail. We first of all start by removing all children of the view and when that's done we run through a loop that then loads the thumbnail, masks it (so we have nice rounded corners) and adds an event listener to the sprite. You'll notice that I'm using a dictionary again here called "idsDic". This will simply store a reference of the sprite being added to the stage so that when it's been clicked on, we know the corresponding YouTube video id to load.

Finally you'll see that the class dispatches a "DataEvent" containing the video id back to its mediator.

Step 17: Creating the Results View Mediator

This mediator will have two simple jobs:

  1. To (re-)build the thumbnails when the query has been run
  2. To pass the video id to our YouTube player

So let's begin by creating the file "" in "src/com/flashtuts/view/":

As I said before, this mediator listens in on 'SearchView.SEARCH_RESULTS' (sent out by the proxy) and sends 'PlayerView.PLAY' once a thumbnail has been created. Now we can get on to creating the player view that will house the YouTube player.

Step 18: Creating the Player View

Before you start with this, you should really read up on the YouTube Player API tutorial I wrote as we'll be using it here. In that tutorial we created a set of classes and a player wrapper. Now copy that player wrapper and paste it in to "src/assets/swf/". As for our classes, I've put them in a simple reusable directory called "src/com/flashtuts/lib/", therefore I've got the class "" in "src/com/flashtuts/lib/display/" and "" in "src/com/flashtuts/lib/events/". This'll mean that you could easily reuse these classes time and time again.

Once you're happy with the location of your YouTube player classes, we'll begin with the player view, so create a new file called "" inside "src/com/flashtuts/view/component/":

As you can see, I start with creating the YouTube player, all within the "init()" function and leave the class to be invisible. I've also used another SWC asset called "CloseButtonAsset". Then we have our two main functions "play()" and "stop()" and they do exactly what it says on the tin.

Now that we're happy with our player view, we can get on with the mediator.

Step 19: Creating Player View Mediator

Again this mediator won't be as complex as you may think. All it's going to do is listen to the notification 'PlayerView.PLAY' and show the player:

Step 20: Deferring the Initialising of the Mediators

We're nearly at the end, but if you've been paying attention you'll see that we haven't yet added the results view mediator or the player view mediator to our application yet. This is because they're not needed at the start of the application, for example, the results view mediator is only needed once a query is being run and the player view mediator is only needed once the results are in and ready to be clicked on. Our application mediator will control all of this, so launch "" - we're going to update the "listNotificationInterests()" and "handleNotification()" functions like so:

You'll see that we're only registering the mediators at certain points during the user's interaction with the application.

And we've done it! Fire up the application and let's have a look..


So there you have it. Using the agility of PureMVC and the YouTube Player API tutorial you can now expand this little application to do many things or integrate the code into a bigger application or web site. The biggest help is Google's GData API service, ever since they've pushed it to YouTube, querying the service has become easier and easier. It's worth having a read of the GData docs as there are lots of things that can be done with Google's products, such as uploading videos to YouTube, using Picasa APIs and Calendar APIs.

Thanks for following along.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.