"Tekken 3 APK Download Best Android Fighting Game Free"
"Discuss with Us on Our Forums"
"30+ Short Love Poems For Her That Will Make Her Cry"

Building in Flash on the YouTube API with ActionScript 3.0

ActionScript is a very powerful programming language used in numerous Adobe Flash and Flex applications. It provides an object-oriented class level environment with many advantages to the average developer. In this example we’ll be constructing a video wall pulling the top videos from YouTube’s Tech feed.

Actionscript Programming

We will mostly be covering basic ActionScript techniques, thus it is not required to be an exceptional whiz at programming. For this tutorial I’ll be using Adobe Flash CS3 with ActionScript 3.0 as the default language.

Building our .FLA File

Each flash project you create should be saved to disk as .fla inside a root directory. I’ve created a new document 630×575 and saved as YouTube.fla.

Getting familiar with the Flash interface may take a little bit of time. Most of the work we’ll be doing is integrated in the lowermost panels. More specifically we’ll be dealing with properties and actions.

Properties will allow you to update the current document width/height and other advanced settings. Actions is where all the real fun happens and where our code is stored. Each layer as a series of keyframes which store ActionScript to manipulate transitions and effects.

Actionscript Programming

You’ll notice a layers panel towards the top above the project stage. The first layer should be named “Layer1”. Change that to Actions and tick the small lock symbol off to the right side. This sets a single layer in our file dedicated to ActionScript code, which means we don’t need to go searching around for anything. Locking just ensures we don’t accidently place elements in that layer.

Designing Page Views

The next step is to create our physical layout. I’ve created a new layer titled “views” which is going to house 6 MovieClips. These will actually become placeholders for the dynamic thumbnail shot YouTube generates with each video.

To create these check insert->new symbol or simply tap F8. Here a new menu comes up asking what type of symbol you are creating. Movie Clip is perfect set along 120px width and 90px height. Once the symbol is made alter the clip’s instance name to “ytThumb” + 0-5 for each clip. So for example the first would be labeled ytThum0, the next ytThumb1 and so forth.

Actionscript Programming

Now we can move back into our actions panel to start really developing. If you are having trouble with creating each movie clip don’t fret. They are not truly necessary at this point, but it does save time to create each instance beforehand.

Beginning the ActionScript Code

Click back on the first keyframe in the Actions layer. From here check the bottom panel and move from properties into actions. The panel will expand much higher and include a text box – this is where our code will go.

To start off we will define a few variables to hold namespace references. These ensure that when pulling data from Google and YouTube’s servers we can interpret the return properly. Also we include a Security.allowDomain call to let Flash know we can trust data downloaded through YouTube.

[sourcecode language=”actionscript3″]
Security.allowDomain("youtube.com","http://youtube.com","www.youtube.com");
var atom:Namespace = new Namespace("http://www.w3.org/2005/Atom");
var gd:Namespace = new Namespace("http://schemas.google.com/g/2005");
var yt:Namespace = new Namespace("http://gdata.youtube.com/schemas/2007");

default xml namespace = atom; // very important!!

var vidCount:int = 6;
var dataArray:Array = new Array();
[/sourcecode]

As an example above we have 3 new namespaces defined as atom, gt, and yt. These correspond with atom RSS feeds and two primary namespaces relating to the YouTube API. By the last line we are setting the default namespace for all XML code to atom.

Without these lines ActionScript will try parsing the return XML from YouTube’s API as plain XML instead of an atom feed. This results in bugs and errors flying around, so it’s much easier to clear this up first.

We are also creating two simple variables towards the very end. vidCount is used to define how many videos we will pull from each feed. dataArray is currently set to an empty array. A future function will pull this data and feed instances of videos into an array list.

[sourcecode language=”actionscript3″]var xmlUrlReq:String = "http://gdata.youtube.com/feeds/api/videos/-/Tech/";
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();

// loader event listener
xmlLoader.addEventListener(Event.COMPLETE, LoadXml);
xmlLoader.load(new URLRequest(xmlUrlReq));
[/sourcecode]

We now have the defining principles for connecting to an XML page. The XML url we are using is defined outright which contains the standard API call. It is malleable in that you can change Tech to any variable returning video results.

For example http://gdata.youtube.com/feeds/api/videos/-/Gaming/ is a possibility for all gaming-related videos. Our xmlLoader will store the functions needed to load this API URL and xmlData is used to store the returning XML code.

Actionscript Programming

After variables are set we need to call our event listener which checks to see when the API has finished loading. At this point we call a new function LoadXml() which is defined next.

Event Handler Calls

Once the loader eventListener has cleared our LoadXml function is called. This will parse all of the data we need out of the YouTube API response and store simple variables for access later. Below is the entire function code.

[sourcecode language=”actionscript3″]function LoadXml(e:Event):void {
xmlData = XML(e.target.data);
var media:Namespace = xmlData.namespace("media");
var gd1:Namespace = xmlData.namespace("gd");
var elms:XMLList = xmlData.entry;

for(var i:int = 0; i < vidCount; i++) {
dataArray.push({});
dataArray[i]["title"] = elms[i].title;
dataArray[i]["coreThumb"] = elms[i].media::group.media::thumbnail[0].@url;
dataArray[i]["vidURL"] = elms[i].media::group.media::player.@url;
dataArray[i]["duration"] = elms[i].media::group.yt::duration.@seconds;
dataArray[i]["viewCount"] = elms[i].yt::statistics.@viewCount;
dataArray[i]["commentCount"] = elms[i].gd::comments.gd::feedLink.@countHint;
dataArray[i]["favoriteCount"] = elms[i].yt::statistics.@favoriteCount;

loadThumbs(dataArray[i]["coreThumb"], i);
loadText(i, dataArray);
}
}
[/sourcecode]

You can see an initial for loop which pulls out elements from each XML file and stores them into an array. This is referenced with each variable call underneath dataArray.push({}).

Setting dataArray[i] would create 6 individual arrays valued dataArray[0-5]. Within each of these we have sub-arrays containing video information.

This includes the core thumbnail, video URL, duration, number of comments, etc. This function is used to pump through all 6 videos inside a loop and extract bits of data from the response. With this data we then create a new array to house all the values we need and pass these into two more functions to display our finished product.

loadThumbs is the first call which requires two parameters. The first param URL is looking for the external jpg thumbnail file while the second holds the index for which video ID we’re on (valued 0-5).

[sourcecode language=”actionscript3″]function loadThumbs(url:String, index:int):void {
var imgURLRequest:URLRequest = new URLRequest(url);
var myImgLoader:Loader = new Loader();
myImgLoader.load(imgURLRequest);

myImgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);

function thumbLoaded(e:Event):void {
var myBitmapData:BitmapData = new BitmapData(myImgLoader.width, myImgLoader.height);
myBitmapData.draw(myImgLoader);

var myBitmap:Bitmap = new Bitmap();
myBitmap.bitmapData = myBitmapData;
switch(index) {
case 0:
ytThumb0.addChild(myBitmap);
break;
case 1:
ytThumb1.addChild(myBitmap);
break;
case 2:
ytThumb2.addChild(myBitmap);
break;
case 3:
ytThumb3.addChild(myBitmap);
break;
case 4:
ytThumb4.addChild(myBitmap);
break;
case 5:
ytThumb5.addChild(myBitmap);
break;
}
}
}
[/sourcecode]

We are pulling in another URL Loader to download each video thumbnail. From here we are actually creating a brand new bitmap file inside of Flash to re-create each image.

The benefit here is we can cache each image and store the contents for another query. This would be useful if you were offering access to multiple YouTube feeds and didn’t want to call a new request every time a new visitor came to the page.

We have another event listener which calls thumbLoaded once the image is finished. Then we create a new bitmap image variable named myBitmap and store the thumbnail data inside. Afterwards there’s a small switch clause breaking down 0-5 for each video ID. The code inside simply targets each Movie Clip and appends addChild() holding each thumbnail image.

Loading Video Text Data

The last step required is pulling video data from our array and adding this onto our stage. For this we’ve written a function loadText which takes the current video ID and also the matching data array.

[sourcecode language=”actionscript3″]function loadText(id:int, vidDataArray:Array):void {
var myFormat:TextFormat = new TextFormat();
myFormat.size = 13;
myFormat.font = "Arial";
myFormat.color = 0x0066FF;
myFormat.underline = true;

var myDescFormat:TextFormat = new TextFormat();
myDescFormat.size = 11;
myDescFormat.bold = true;

var mytext = this[‘ytTitle’+id];
var mydesc = this[‘ytDesc’+id];

var vidTitle:String = vidDataArray[id]["title"];
var vidUrl:String = vidDataArray[id]["vidURL"];
var vidDur:int = vidDataArray[id]["duration"]; // duration in seconds
var vidDurMin:String = Math.floor(vidDur/60) + ":" + vidDur%60; //duration in minutes
var vidViews:String = splitNumber(vidDataArray[id]["viewCount"]);
var vidComms:int = vidDataArray[id]["commentCount"];
var vidFav:int = vidDataArray[id]["favoriteCount"];

mytext.wordWrap = true;
mytext.defaultTextFormat = myFormat;

mydesc.defaultTextFormat = myDescFormat;
mydesc.textColor = 0x333333;
mydesc.text = "Time: " + vidDurMin + "\r";
mydesc.text += "Views: " + vidViews + "\r";
mydesc.text += "Comments: " + vidComms + "\r";
mydesc.text += "Favorites: " + vidFav + "\r";

var htmlstring:String = ‘<a href="’ + vidUrl + ‘" target="_blank">’ + vidTitle + ‘</a>’;
mytext.htmlText = htmlstring;

}
[/sourcecode]

The beginning lines use a variable myFormat to create a new text formatting. This is a dynamic way to create text input data and import the settings into a project without physically adding any onto the stage. There is no real benefit of this way other than saving file space. However it is good practice to introduce yourself to both methods and choose whichever works best!

Actionscript Programming

We are creating new variables to hold the video data. More specifically we will be accessing the video’s title, URL, duration (and convert this from seconds to minutes), total views, total comments, and total favorites.

Using myText as a new text area we can append these elements with htmlText. From this each video ID will loop through the XML event handler and add all the images and text onto stage.

With this should complete our code! You can test your movie from control->test movie or ctrl+enter on Windows. If you’d like to reference my project code you can download the archive here. Included are both the .fla file and the .swf finished movie product.

This has been an introduction into developing over YouTube’s API. The project was created for the purpose of writing in many different structures and testing different programming styles. ActionScript is very robust and provides an excellent platform for API data manipulation.

[learnmore link=”http://media.pelfusion.com/code/actionscript-youtube-api.zip”] Download Source [/learnmore]

Reply To: Building in Flash on the YouTube API with ActionScript 3.0




<a href="" title="" rel="" target=""> <blockquote cite=""> <code> <pre> <em> <strong> <del datetime=""> <ul> <ol start=""> <li> <img src="" border="" alt="" height="" width="">

CLOSE