Youtube Data API AS3 – First Tutorial

Hi everyone,

In this tutorial I will demonstrate how to use the YouTube Data API AS3 Library to:

  • search for videos using a keywords, categories and tags;
  • demonstrate how to distinguish between feeds returned to you by the API by using the requestId;
  • get information from the result feed, in this case a VideoFeed object. We will get the video, it’s main URL, then go through the different thumbnails available for a specific video.

So let’s get started

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
package ca.newcommerce.youtube
{
	// the different imports we will be needing
	import ca.newcommerce.youtube.data.ThumbnailData;
	import ca.newcommerce.youtube.data.VideoData;
	import ca.newcommerce.youtube.events.VideoFeedEvent;
	import ca.newcommerce.youtube.feeds.VideoFeed;
	import ca.newcommerce.youtube.iterators.ThumbnailIterator;
	import ca.newcommerce.youtube.webservice.YouTubeClient;
 
	// our class
	public class SearchSample
	{
		// the web service client reference
		protected var _ws:YouTubeClient;
 
		// an id to identify our request
		protected var _requestId:Number;

So far we’ve defined our class, SearchSample, and two member variables: _ws (which will contain a reference to the YouTubeClient singleton) and _requestId (to store the unique id associated with our specific request).

Next we will get a reference to the YouTubeClient class, listen for the proper event, launch our search request and store the requestId associated with it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
		// the constructor to our sample
		public function SearchSample()
		{
			// get a reference to the YouTubeClient instance
			_ws = YouTubeClient.getInstance();
 
			// listed for the proper event to be fired by the client,
			// the function "doSearchResults" will be called once the results are received
			_ws.addEventListener(VideoFeedEvent.VIDEO_DATA_RECEIVED, doSearchResults);
 
			// search for the string : "american idol"
			// while not specifying an author
			// while not specifying any categories
			// look for videos tagged with "music"
			// and not tagged with "male"
			// order by view count
			// include restricted material
			// finally store the resulting requestId inside of SearchId.
			_requestId = _ws.getVideos("american idol", "", null, null, ["music"], ["male"], YouTubeClient.ORDER_BY_VIEWCOUNT, YouTubeClient.RACY_INCLUDE);
 
		}

Now on with the event handler, doSearchResults. We will:

  • make sure we are treating the right request, since YouTubeClient is a singleton, this can become important when you have multiple calls being made from different places in your program.
  • get a reference to the VideoFeed object contained inside of the VideoFeedEvent object passed as a parameter to the event handler.
  • create a variable to contain the VideoData objects describing the videos received in the results
  • iterate through the first set of results (since we are getting the first 50 by default
  • see some useful variables such as the Title of the video and it’s author’s name
  • get a reference to the ThumbnailIterator which will give us access to all available thumbnails
  • create a variable to contain ThumbnailData objects which describe each thumbnail available

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
		// our function definition, note the evt variable is of type VideoFeedEvent
		protected function doSearchResults(evt:VideoFeedEvent):void
		{
			// check to see if this request's response is the right one
			if(_requestId == evt.requestId)
			{
				// get a reference to the VideoFeed
				var feed:VideoFeed = evt.feed;
 
				// prepare a variable to hold the individual Video's data.
				var video:VideoData;				
 
				// iterate through the feed results
				while(video = feed.next())
				{
					// video title
					video.title;
 
					// video author's name
					video.authors.first().username;
 
					// get a reference to the ThumbnailIterator
					var tnIt:ThumbnailIterator = video.media.thumbnails;
 
					// prepare a variable to hold the individual thumbnail's data
					var tn:ThumbnailData;
 
					// iterate through each thumbnail
					while(tn = tnIt.next())
					{
						// thumbnail url
						tn.url
 
						// thumbnail width
						tn.width;
 
						// thumbnail height
						tn.height;
 
						// thumbnail time sequence
						tn.time;
					}
				}
			}
			else
			{
				trace("this request:"+evt.requestId+" is not ours. we'll wait for the next one");
			}
		}
	}	
}

That’s it folks! The project is now available at Google Code, here: http://code.google.com/p/as3-youtube-data-api/

I could use help with documentation, if anybody feels up to the task, leave your email or contact info in a comment!

18 thoughts on “Youtube Data API AS3 – First Tutorial

  1. Hello, Im trying to play with this great library but i cant make it work on browser…inside flash everything its fine. Its crossdomain working???

    thanks

  2. Getting the following error on doLogin:
    WSClient.doHttpStatus:200
    doLogin
    ArgumentError: Error #2096: The HTTP request header Authorization cannot be set via ActionScript.
    at flash.net::URLStream/load()
    at flash.net::URLLoader/load()
    at ca.newcommerce.youtube.webservice::YouTubeClient/runLoader()
    at ca.newcommerce.youtube.webservice::YouTubeClient/rate()
    at ca.newcommerce.youtube::Test/doLoggedIn()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at ca.newcommerce.youtube.webservice::YouTubeClient/doLogin()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

    Can you advise please? Thanks

  3. Alan,

    I am working on a version which uses a AMFPHP Proxy. This problem you had is caused by the security sandbox from the Flash Player, by using a proxy we have complete freedom. In PHP and most other programming languages you don’t have these (stupid) limitations. I use cURL to make the requests, and return the responses using AMFPHP. It works quite nice. I recently posted on it. The API will be updated shortly.

  4. Pedro,

    this problem is due to the crossdomain.xml policy file found on i.ytimg.com, over which I have no control. I suggest posting this comment in the google group on the Youtube Data API developer forum.

  5. Pingback: dehash » YouTube API Resources «

  6. Hi,

    i really liked this AS3 Classes, but i can´t download from code.google…there is a problem? -

  7. Hello,
    I’m a AS3 new beginner and I’ve read your sample code in this article. But when I press Ctrl + Enter to test, it show: “Error:5000, it must have sub-class “flash.display.MovieClip”
    Then I import flash.display.MovieClip, but still pop the same error code 5000. Could you kindly give me some suggestions?
    Thanks a lot!!

  8. Hi,

    I tried to use the method getVideo from YouTubeFeedClient class, but I have the next message:

    WSClient.doHttpStatus:200
    doVideoLoaded

    The code it is the follow:

    _ws = YouTubeClient.getInstance();
    _ws.addEventListener(VideoFeedEvent.VIDEO_DATA_RECEIVED, doSearchResults);

    _requestId = _ws.getVideos(“uEGPF1be6RM”);

    anyone know, what happend?

    Reagards.

  9. Pingback: Tutorials | AS3 and AMFPHP Roundup « Flash Enabled Blog

  10. Hi!
    Impressive work indeed, and its really amazing the kind of interaction with Youtube you can acchieve.

    I am having a really annoying problem though, where amidst all the data can I retrive the URL to the netstream I need to connect my Video player to actually play the stream?

    TIA
    Niklas Wörmann
    Sweden

  11. Pingback: Flash Tips » AS3 and AMFPHP roundup

  12. Okay…I think I must be a complete idiot, cause I’m really having a hard time getting this. (Though I’m making progress)

    I’m trying to get a the ten most recently uploaded videos from a particular youtube account, and I just can’t seem to make it happen.
    (I think I need to use “VideoFeedEvent.VIDEO_DATA_RECEIVED”, but I’m not sure how to do it…)

    So far, this is the most mack-daddy site that I’ve found for the youtube API. Can somebody please help me? PLEASE!!!

  13. Okay…I figured it out. The latest download (0.95) gets a little confused, because the test files and classes are trying to access YouTubeClient.as and it doesn’t exist anymore. (They are now YouTubeDataClient.as & YouTubeFeedClient.as)

    Simply switch it to the most appropriate file and you’ll be golden.

    Now, if I can just figure out how to attach my new content to items on my stage I’ll be crazy happy!

  14. Two days later…still trying to figure out the getAt method. ARGH!!!

    I think that’s how I need to call specific lines from the feed.

Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *

55,282 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>