Archive for category ActionScript 3
Sending byteArray (image) and variables to server-side script as POST data in AS3
Posted by zedia.net in ActionScript 3 on July 21st, 2010
A couple things here, I first talked about how to send an image and variables to the server (at the same time) on this post, but it felt a bit weird, the file had no name to retrieve it and the variables were sent as GET. Now while working a with a new colleague, he showed me this code that for him was nothing but for me was amazing. It is a little library called UploadPostHelper made by Jonathan Marston back in 2007 (2007! why didn’t someone talk to me about this library before!!!).
Anyway here is a little code snippet showing how to use it:
var jpegEncoder:JPGEncoder = new JPGEncoder(85); //using the JPGEncoder from as3corelib var jpegBytes:ByteArray = jpegEncoder.encode(myPicture.bitmapData); //encoding a Bitmap into a ByteArray var urlRequest : URLRequest = new URLRequest(); urlRequest.url = "THE URL OF YOUR SERVER SIDE SCRIPT"; urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary(); urlRequest.method = URLRequestMethod.POST; //now create an object with the variables you want to send as POST var postVariables:Object = {variable1Name:variable1Data, variable21Name:variable2Data, variable3Name:variable3Data} urlRequest.data = UploadPostHelper.getPostData( 'image.jpg', jpegBytes,"filedata", postVariables); //here is where the magic happens, filedata will be the name to retrieve the file urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) ); //from here it is just a normal URLLoader _pictureUploader = new URLLoader(); _pictureUploader.dataFormat = URLLoaderDataFormat.BINARY; _pictureUploader.addEventListener( Event.COMPLETE, _onUploadComplete, false, 0, true ); _pictureUploader.load( urlRequest );
How easy and beautiful is that?
So can get the code for the UploadPostHelper at the bottom of this post or I have made a zip file with the .as file here.
Dude, 2007!
Drawing Bezier tool using Robotlegs
Posted by zedia.net in ActionScript 3 on June 17th, 2010
I came back from FITC Toronto with a lot of ideas for new posts and this is the last one of them. But fear not this is a first article in what will probably be a serie of 3 because it would otherwise be too long (or I wouldn’t have the patience to write it). So while at FITC, I went to a presentation be the guys at Firstborn about how they were often making tools instead of doing things by brute force. Well the idea stuck with me.
In the current project that I am working on, there was a part where I needed the coordinates of points along a path. The brute force way was to estimate the next point myself and to compile to see if I was right, repeat until I had all the coordinates I needed. Very tedious and boring task and the path could change often so there was high chances that I would redo this process often. What better time to start making a tool! Well it turn out that my project changed so much that that part wasn’t in it anymore… But it still makes a great topic for this blog.
Let me start by showing you what will be the result of this first post. (Below is not juste whitespace, click in it to ad points. You can select a path to make a control point appear, drag the control point to make a curve).
As you can see this is pretty bare bone. But the good thing about that is that you can use this as the base of multiple tools.
I built this using Robotlegs. If I am going to build something for myself, might as well learn (or train) a few things on the way. Plus, I think Robotlegs is very well suited for application style projects. Now that being said, using that kind of framework (MVC) will require you to create a lot of extra classes but in the end you will understand what you gain by doing so. Out of all these, 4 of them are really important. The Model, where you will keep all information on paths and points at all time and three View classes; one for the clickable area layer, one for the paths layer and one for the point layer.
The easiest of all of them is the clickable are layer. It’s job is just to register clicks and tell the framework where something has been clicked. This could have been done otherwise, but since we will want to layer stuff (points are over paths) plus we will want to select points and path to move or curve them, it is just easier to create a view just to register clicks on the unused stage and put that view in the back off our application.
package com.zedia.drawingtool.view.components { import com.zedia.drawingtool.events.PointEvent; import com.zedia.drawingtool.model.objects.PointObject; import flash.display.Sprite; import flash.events.MouseEvent; /** * @author dominicg */ public class DrawingArea extends Sprite { public var pointArray:Array; private var _pathArray:Array; public function DrawingArea() { graphics.beginFill(0xffffff); graphics.drawRect(0, 0, 550, 400); graphics.endFill(); addEventListener(MouseEvent.MOUSE_DOWN, _onMouseClick, false, 0, true); } private function _onMouseClick(event : MouseEvent) : void { dispatchEvent(new PointEvent(PointEvent.ADD_POINT, new PointObject(event.stageX, event.stageY))); } } }
Our second view is the one that handles the points. Points are simple visual objects, they are just circles placed at a x and y coordinate. So when the user clicks on the clickable layer, the point view is notified and a circle is added where the click was registered. Another functionality that is added is that you can drag a point to move it around the stage. One thing to notice is that whenever a point is moved, it tells the framework about it so that the Model is always up to date and so that the path layer can display the paths correctly.
package com.zedia.drawingtool.view.components { import com.zedia.drawingtool.events.PointEvent; import com.zedia.drawingtool.model.objects.PointObject; import flash.display.Sprite; import flash.events.Event; /** * @author dominicg */ public class PointLayer extends Sprite { private var _pointVector:Vector.<PathPoint>; public function PointLayer() { _pointVector = new Vector.<PathPoint>(); } public function addPoint(point:PointObject):void{ var pathPoint:PathPoint = new PathPoint(); pathPoint.addEventListener(PointEvent.POINT_MOVED, _onPointMoved, false, 0, true); pathPoint.x = point.x; pathPoint.y = point.y; addChild(pathPoint); _pointVector.push(pathPoint); } private function _onPointMoved(event:Event) : void { dispatchEvent(new PointEvent(PointEvent.POINT_MOVED, new PointObject(PathPoint(event.target).x, PathPoint(event.target).y, _pointVector.indexOf(PathPoint(event.target))))); } } }
Now this is the last of the view class: the PathLayer. It is also the most complicated of the three view classes because a path is a complex object. It is comprised of a start point, an end point and a control point. With those you can draw a curve using the curveTo method from the AS3 drawing API. Here is the code:
package com.zedia.drawingtool.view.components { import com.zedia.drawingtool.events.PathEvent; import com.zedia.drawingtool.model.objects.PointObject; import com.zedia.drawingtool.model.objects.PathObject; import flash.display.Sprite; import flash.events.Event; /** * @author dominicg */ public class PathLayer extends Sprite { private var _pathVector:Vector.<Path>; private var _selected:int = -1; public function PathLayer() { _pathVector = new Vector.<Path>(); } public function addPath(pathObject:PathObject):void{ var path:Path = new Path(pathObject.firstPoint, pathObject.secondPoint, pathObject.controlPoint); path.addEventListener(PathEvent.PATH_CLICKED, _onPathClicked, false, 0, true); path.addEventListener(PathEvent.CONTROL_POINT_MOVED, _onControlPointMoved, false, 0, true); addChild(path); _pathVector.push(path); } private function _onControlPointMoved(event : Event) : void { dispatchEvent(new PathEvent(PathEvent.CONTROL_POINT_MOVED, new PathObject(new PointObject(0,0,0), new PointObject(0,0,0), _pathVector.indexOf(Path(event.target)), Path(event.target).controlPoint))); } private function _onPathClicked(event : Event) : void { if (_selected > -1){ _pathVector[_selected].deselect(); } _selected = _pathVector.indexOf(Path(event.target)); } public function updatePaths(updatedPathVector : Vector.<PathObject>) : void { for (var i : int = 0; i < updatedPathVector.length; i++) { _pathVector[updatedPathVector[i].id].update(updatedPathVector[i]); } } public function deselectAll():void{ if (_selected > -1){ _pathVector[_selected].deselect(); _selected = -1; } } } }
You will find more information about paths in the Path class inside the view folder.
Finally the last important class is the Model. This is where you keep information about the state of the application. With the information stored in the Model you can recreate exactly how the application is right now, which is really practical if you want to save the state to a file or export data. As you will see, it is mostly saving a data representation of visual objects in our views (points and paths).
package com.zedia.drawingtool.model { import com.zedia.drawingtool.events.PathEvent; import com.zedia.drawingtool.events.PointEvent; import com.zedia.drawingtool.events.PathVectorEvent; import com.zedia.drawingtool.model.objects.PathObject; import com.zedia.drawingtool.model.objects.PointObject; import org.robotlegs.mvcs.Actor; import flash.geom.Point; /** * @author dominicg */ public class DrawingModel extends Actor { private var _pointVector:Vector.<PointObject>; private var _pathVector:Vector.<PathObject>; public function DrawingModel() { _pointVector = new Vector.<PointObject>(); _pathVector = new Vector.<PathObject>(); } public function addPoint(point:PointObject):void{ point.id = _pointVector.length; _pointVector.push(point); dispatch(new PointEvent(PointEvent.ADD_POINT_APPROVED, point)); var pointLength : int = _pointVector.length; if (_pointVector.length > 1) { var controlPoint:Point = new Point((_pointVector[pointLength - 1].x - _pointVector[pointLength - 2].x)/2, (_pointVector[pointLength - 1].y- _pointVector[pointLength - 2].y)/2); _pathVector.push(new PathObject(_pointVector[pointLength - 2], _pointVector[pointLength - 1], _pathVector.length, controlPoint)); dispatch(new PathEvent(PathEvent.ADD_PATH_APPROVED, _pathVector[_pathVector.length -1])); } } public function updatePoint(point : PointObject) : void { trace (point.id); _pointVector[point.id].x = point.x; _pointVector[point.id].y = point.y; //Update paths now var resultingPathVector:Vector.<PathObject> = new Vector.<PathObject>(); if (point.id == 0) { _pathVector[point.id].firstPoint = point; resultingPathVector.push(_pathVector[point.id]); } else if (point.id == _pointVector.length - 1){ _pathVector[point.id - 1].secondPoint = point; resultingPathVector.push(_pathVector[point.id - 1]); } else { _pathVector[point.id].firstPoint = point; resultingPathVector.push(_pathVector[point.id]); _pathVector[point.id - 1].secondPoint = point; resultingPathVector.push(_pathVector[point.id - 1]); } dispatch(new PathVectorEvent(PathVectorEvent.UPDATE_PATHS, resultingPathVector)); } public function updateControlPoint(path : PathObject) : void { _pathVector[path.id].controlPoint = path.controlPoint; } } }
Well that is it for now. You can download the source code below and see the classes that I didn’t talk about. This is all good but this tool right now just draw paths but it doesn’t transform or export the data in any way. This will be the topic of a next post.
Starting out with Alchemy (on a Mac)
Posted by zedia.net in ActionScript 3 on May 13th, 2010
So I’m a PC that now works on a Mac. It’s not my choice, but I went along with it to experience the Mac side of things. I don’t hate it, but I don’t like it that much either. That being said, it means that I am a complete noob user. For the past 2 days, I have been trying to make Alchemy work (compiler that let’s you compile C and C++ libraries to a SWC that can be used in Flash) and it wasn’t all that easy.
First I’m going to point you to two articles on how to setup Alchemy. The first one can be found on Adobe Labs and has a detailed list of steps to complete in order to make Alchemy works. The second one is from zaalabs and it gives further information to get it done.
Now, even with those articles I had a lot of trouble to get it to work, mostly because I don’t know a lot about command line stuff. The first thing that confused me was the mention of a bash / shell / terminal interchangeably. Now, I know there is a difference between all of those, but in this case they all mean the terminal. You can access the terminal by going to Applications and inside the Utilities folder you’ll find the terminal.
The second thing that I didn’t understand was how to add something to the system path. This is also referred later on as adding to your paths. This means editing a file that will put a certain path to be handled like a system path so that you can access whatever is in that folder from any directory. To do so you have to edit a certain file named .profile. The problem that I had was that looking around the interweb for adding to the system path I found that I had to edit a file named .bash_profile. Well it turns out that both works but you just need one of those, if you put some info in one and some info in the other, just one of the file is going to be used so it won’t work. Just use .profile as mentioned in Adobe doc. Now that file is a hidden file (it starts with a “.”) and to see if it exist, in terminal, you must, right after you open it, write “ls -a”, the -a option will show you file that starts with a “.”. If the file .profile doesn’t exist you can create it using an editor like pico by writing “pico .profile”, writing what you need in it and saving the file. Just to help out, here is what my .profile file looks like after I have completed all the steps:
source /Users/dominicg/library/Alchemy/alchemy-setup PATH=$PATH:/Users/dominicg/Flex3/bin:/Users/dominicg/library/Alchemy/achacks export PATH
Last note to be sure everything works, you need to use the Flex SDK 3.2 and no other version. That particular SDK can be found here.
Well I hope this will help some of you. I pretty much shifted focus from Alchemy since I started writing this article, but I am sure I will get back to it at some point.
Create your own ColorPicker using a Bitmap
Posted by zedia.net in ActionScript 3 on April 12th, 2010
A while ago I did an application that required a colorpicker, I didn’t know much at the time so I chose to use the ColorPicker component that came with Flash CS3. That component is ok but it kinda is limited. After a little while I wanted more than what it was providing me. I wanted to imitate a bit the colorpicker that you can find in Photoshop. It turns out that it is pretty easy to do so. All you need is a picture of a color gamut and you are all set.
What we are going to do in short is transform this image of a color spectrum (bitmap) into a Sprite and when the mouse is over that Sprite, get the color that is right under the mouse. For the image of the color spectrum i’ll use a picture I found on wikipedia and just resize it a bit. All you need is a picture with enough color on it, you could also use a picture of your dog if you wanted but the goal is more a picture with some organisation in the color.
Here is the picture I used:
Now all you need to do is add a little bit of code to it and you have the basis of a color picker. The method that will do most of the work for us is a method from BitmapData called getPixel. You basically tell that method which pixel in the Bitmap, by providing it’s x and y coordinates, and getPixel will return you the color of that pixel. Now, this method returns the color as a unsigned integer that is not so legible, so we will have to convert that to an hexadecimal base so that we can relate to it.
But to be able to use this method (getPixel) we will need a BitmapData of the spectrum. In Flash, you can turn most MoviClip into BitmapData by using the method draw. I’ll do it in the following code snippet.
Here we go:
//Add the mouse funcitonality to the color picker myColorPicker.addEventListener(MouseEvent.ROLL_OVER, onRollOver, false, 0, true); myColorPicker.addEventListener(MouseEvent.ROLL_OUT, onRollOut, false, 0, true); var myBitmapData:BitmapData = new BitmapData(myColorPicker.width, myColorPicker.height); myBitmapData.draw(myColorPicker); function onRollOver(event:MouseEvent):void{ myColorPicker.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove, false, 0, true); } function onRollOut(event:MouseEvent):void{ myColorPicker.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove); } function onMouseMove(event:MouseEvent):void{ var myColor:uint = myBitmapData.getPixel(myColorPicker.mouseX, myColorPicker.mouseY); trace (myColor.toString(16)); //The toString(16) convert the uint into a legible hexadecimal representation ike in Photoshop }
Event bubbling in the ActionScript world
Posted by zedia.net in ActionScript 3 on April 1st, 2010
I have been putting off writing this post but now that I am in between jobs I thought it was the good time. Well, I have been putting this off because it seemed like a good topic at the time, but eventually the concept of event bubbling became easy to me and than I felt no point in writing about it, but I guess it is not the same for every one. So here is my take on the subject.
Event bubbling in general
Event bubbling is not a concept that is particular to ActionScript but it is handled in special way by it. Event bubbling inscribe itself in an event model where events are dispatched and listened for. The bubbling part refers to event going up like bubbles in water (that’s my interpretation of the name). It doesn’t really make an sense also outside of the object oriented programming realm because of the need of encapsulation. It also implies some sort of composition because an object(Class (i’ll refer to #1 later)) needs to have another object(#2) created inside of it in order for it(#1) to listen to events dispatched by the second object(#2). Thus creating a hierarchy and enabling the possibility of event bubbling.
So in the preceding example I had 2 levels of hierarchy and every thing was fine, no need for event bubbling when object(#1) can easily listen to objects(#2) events. Now if I had 3 levels of hierarchy, object(#3) is inside of object(#2) which is inside of object(#1) we could use event bubbling to save some coding. Object(#1) can listen to object(#2) and object(#2) can listen to object(#3) but without adding code or making object(#3) public inside object(#2), object(#1) cannot receive the events from object(#3). Oh my, I hope this doesn’t sound too complicated with all those number signs. Ok so here we get to the concept, if we enabled the bubbling of events when dispatched in object(#3), the events would the go up (bubble) the hierarchy and make there way to object(#1) through object(#2) as if object(#2) had dispatched them. Keep on reading it gets easier (I hope).
Event bubbling in ActionScript
Now in the ActionScript world, event bubbling works in a particular way; it is tied to the Display List (The “Display List” is the hierarchy of graphical objects in your movie to be displayed on screen at runtime) . Meaning you cannot have event bubbling, using the event system of ActionScript, if your dispatcher is not added to the Display List (you didn’t do addChild to a children of the Stage to add your object). You can dispatch events just fine, but they won’t bubble even if you set bubbling to true.
What is cool with the Diplay List is that you can really picture the hierarchy using the mathematical structure of the tree (well if you flip it upside down it looks like a tree). Here is an visual example.
Ok, not my best drawing, but I don’t have Photoshop right now; I used Aviary for the first time and I can say it is quite nice to try, not Photoshop but I think you have to get used to it in order to see its full potential.
Now in that picture, if DisplayObject6 was to dispatch an event with bubbling to true here is who could listen to it.
- DisplayObjectContainer5 could listen to it; it is the direct parent of DisplayObject6, no need for event bubbling here
- DisplayObjectContainer3 could listen to it by adding a listener on DisplayObjectContainer5
- DisplayObjectContainer1 could listen to it by adding a listener on DisplayObjectContainer3
- The Stage (or Main class) could listen to it by adding a listener on DisplayObject1
Every body in the chain up from that object could listen to it (all at the same time if you wanted, doing each their different action upon receiving the event). If at some point you would like to stop the bubbling of the event you can always do so by using the stopPropagation method in the event class in your event handler method.
So as you see event bubbling is not a really hard concept and can save you from writing some boring repetitive code. (event handler methods). Anyway I might revisit this post later on to fix some things because I don’t think I was clear enough. Maybe I’ll had some code.
Using the ActionScript 3 YouTube Api
Posted by zedia.net in ActionScript 3 on March 2nd, 2010
On October 14th YouTube released a new version of it’s API for Flash. This version would support ActionScript 3. Previously discussed on here was the library TubeLoc which was basically an AS3 wrapper around the ActionScript 2 API. Now the new API does all TubeLoc pertmitted us to do and even more.
Well loading a YouTube video in ActionScript 3 has never been easier and there is nothing to download (which has its downside in some way)to get started.
Here is all the code needed to load a YouTube movie:
package { import flash.display.DisplayObject; import flash.display.Loader; import flash.display.Sprite; import flash.events.Event; import flash.net.URLRequest; public class Main extends Sprite { private var _loader : Loader; private var _player : Object; public function Main() { _loader = new Loader(); _loader.contentLoaderInfo.addEventListener(Event.INIT, _onLoaderInit, false, 0, true); _loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3")); } private function _onLoaderInit(event : Event) : void { _player = _loader.content; _player.addEventListener("onReady", _onPlayerReady, false, 0, true); addChild (DisplayObject(_player)); _loader.contentLoaderInfo.removeEventListener(Event.INIT, _onLoaderInit); _loader = null; } private function _onPlayerReady(event : Event) : void { _player.removeEventListener("onReady", _onPlayerReady); // Once this event has been dispatched by the player, we can use // cueVideoById, loadVideoById, cueVideoByUrl and loadVideoByUrl // to load a particular YouTube video. _player.setSize(640, 360); _player.loadVideoById("D2gqThOfHu4"); } } }
You can compile this code as an ActionScript project or make it the Document class of an fla in the Flash IDE to make it work.
So you start by loading the player using a normal Loader. Once the player is loaded you have to wait for it to send the onReady event before you can interact with it. Once this is done you can call all of the function from the API.
The previous code would load the chromeless YouTube player; but if you wanted to use the controls from YouTube you would only have to replace one line:
//_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));//replace this line with the following _loader.load(new URLRequest("http://www.youtube.com/v/VIDEO_ID?version=3"));//replace VIDEO_ID with the id of the video you want to load in the previous case :"D2gqThOfHu4" //also you can comment the following line if you don't want the video to start automatically: _player.loadVideoById("D2gqThOfHu4");
All the functionalities that where accessible with TubeLoc are also accessible with the AS3 API and there are some more. Those are methods to control the quality setting of the loaded movie. You can set the quality to small, medium, large and hd720. To do so you have 3 methods on the player. getPlaybackQuality():String will return the quality of the video currently playing. setPlaybackQuality(suggestedQuality:String) enables you to set the quality. Finally, getAvailableQualityLevels():Array will return you all the possibilities of quality that you can set the current video to.
For more information on the topic, refer to the API : http://code.google.com/apis/youtube/flash_api_reference.html
Skinning the ComboBox Flash component
Posted by zedia.net in ActionScript 3 on February 17th, 2010
This post is more for me because I keep forgetting how to do this. For my defense I have to say that it is not exactly the first thing that comes to mind when you are trying to change the font in the ComboBox component, but at least I won’t have to remember in which project I did it; I’ll just turn to my friend Google and type : comboBox + zedia.
Editing the visual is mostly easy inside of flash but my main problem is always the fonts. In a previous post I talked about fonts in Flash in general, this one will use that as a base and apply it to the ComboBox. Here is the code to change the font in the textfield and the dropping list:
var myFormatWhite:TextFormat = new TextFormat(); myFormatWhite.font = "DFC GillSansLight"; myFormatWhite.size = 15; myFormatWhite.color = 0xffffff; var myFormatBeige:TextFormat = new TextFormat(); myFormatBeige.font = "DFC GillSansLight"; myFormatBeige.size = 14; myFormatBeige.color = 0xa18c52; comboBox.textField.setStyle("embedFonts", true); comboBox.textField.setStyle("textFormat", myFormatWhite);< comboBox.dropdown.setRendererStyle("embedFonts", true); comboBox.dropdown.setRendererStyle("textFormat", myFormatBeige); comboBox.prompt = "Province"; //default value that won't show in the dropdown comboBox.addItem( { label:"New Brunswick", data:"New Brunswick" } ); comboBox.addItem( { label:"Nova Scotia", data:"Nova Scotia" } ); comboBox.addItem( { label:"Ontario", data:"Ontario" } ); comboBox.addItem( { label:"Prince Edward Island", data:"Prince Edward Island" } );
My problem was mostly with the setRendererStyle method; not that obvious. I also put the code for adding items in the ComboBox and to have a default text in it that doesn’t show in the dropdown. Now the next bit of code if to check, when you used ComboBox.prompt, if something was selected:
if (comboBox.selectedIndex == -1) { //show error message because comboBox wasn't changed }
P.S. all this code assumes that I have dragged the component to the stage in the Flash IDE
More on preloaders: passing the loaderInfo
Posted by zedia.net in ActionScript 3 on January 19th, 2010
I previously made 2 posts on the topic of preloaders (The right way to do a preloader in AS3, External Preloader; more complex cases), well this post will be a continuation of those. And one that I believe not everyone will agree with me. I know that because I didn’t agree with it at first but the more I thought about it the more it felt right.
When it comes to code I’m a bit of a fascist, I have trouble accepting habits of other coders if they are not the same as mine. So when I see something different my first reaction is to frown upon it (I am talking just about code; I am a very open minded person). When I first saw this mean of passing variables from the preloader to the main application that a coworker was doing I didn’t quite like it.
In the post about the more complex preloaders, I showed how to use an interface to pass data from the preloader to the loaded (main) movie. Now this part of the code is still the same. What changes is that instead of passing the flashVars (variables that are passed to the flash from the html embed code or javascript) individually inside fo the init method of the Main class (also in the interface), we pass them all together by giving the root.loaderInfo instead.
I already know what you are going to say: this is not strictly typed so it is bad. I know, I know, but if you think about it a bit you see that at some point the flashVars are not typed anyway; when they transition from html to flash. So what is the harm of perpetuating this just one level more? In the init method inside the Main class, the first thing I do is that I type the parameters passed, so I do end up typing my variables.
Now, you’re going to ask what do you gain from this? Well, since the preloader is an external file, every time you are going to pass more variables to the Flash from the HTML, you will have to modify 3 files : the preloader.fla, the IMain.as and the Main.as. Now if you pass the loaderInfo instead of the individual flashVars, you will only need to modify the Main.as since it is there that you type the variables. You completely bypass the preloader, which in a way make sense since your preloader doesn’t need to know about your application, all it does is to load it. once your preloader is completed you don’t ever have to touch it again.
Here is some code to illustrate this. In the preloader :
var mainContent:IMain; function onLoadComplete(event:Event):void{ // this would be the function that the loader would call when the loading is completed mainContent = IMain(loader.content); addChild(Sprite(mainContent) ); mainContent.init( root.loaderInfo); }
And in the Main class :
package{ import com.zedia.interfaces.IMain; import com.display.Sprite; import com.display.LoaderInfo; public class Main extends Sprite implements IMain{ public function init(loaderInfo:LoaderInfo):void{ var flashVar1:String = String(loaderInfo.parameters.flashVar1); var flashVar2:Number = Number(loaderInfo.parameters.flashVar2); //do something with the FlashVars } } }
How to load a YouTube movie into Flash using TubeLoc
Posted by zedia.net in ActionScript 3 on October 26th, 2009
I have written this article a while back for FFDMag, but I thought I would put it here also. It lost a bit of relevance because YouTube now has an AS3 API for its player, but if you work on a project that uses TubeLoc, I think this article can be useful.
What you should know:
- Basic knowledge of ActionScript
- Basic knowledge of YouTube
What you will learn:
- How to load YouTube videos into Flash
- How to use the TubeLoc library to control those videos
Embedding a YouTube movie in an HTML page is an easy task, but we can’t say the same about embedding a YouTube clip in a Flash/Flex website. TubeLoc, an opensource library, is there to make that easier.
Before TubeLoc, you could always go and try to find the address of the FLV the YouTube player is loading and load that FLV directly into your Flash application, but YouTube changes the address almost every night, so it wasn’t a very long term solution. Another problem that TubeLoc solves is the fact that the YouTube player is made in ActionScript 2 and most projects now are using ActionScript 3, so it was hard interfacing with the player. TubeLoc is a wrapper around the the AS2 player and show us an AS3 API, but behind the scene it handles the YouTube player using local connection.
To get started with TubeLoc you will first need to download the library at this address:
http://code.google.com/p/tubeloc/
There you will also find a great demo showing you what you can do with the library. You can pause, stop, play, mute, seek, change the volume, change the the size of the video and even load the video without the YouTube player chrome (so you won’t see the play button from YouTube the only thing that will be there is the YouTube logo at the bottom right of the video).
In the zip file that you download from the previous url, copy the “com” folder located in the “as3/src” folder in the same directory where your FLA will be. Also copy there the file as2_tubeloc.swf from the folder “as3/lib”. Now we can get coding. Here is all that is needed to load a YouTube movie into Flash:
import com.enefekt.tubeloc.MovieSprite; import com.enefekt.tubeloc.event.*; var youtubeMovie:MovieSprite = new MovieSprite(null, true); youtubeMovie.addEventListener(PlayerReadyEvent.PLAYER_READY, onPlayerReady); addChild(youtubeMovie); function onPlayerReady(event_p:PlayerReadyEvent):void { //it's just cleaner to remove listener that won't be used again youtubeMovie.removeEventListener(PlayerReadyEvent.PLAYER_READY, onPlayerReady); //you can set the size of the movie this way youtubeMovie.width = 370; youtubeMovie.height = 276; youtubeMovie.loadVideoById("tprMEs-zfQA"); }
The first lines import the library from the “com” folder we copied. After that it creates the MovieSprite. The first parameter is the id of the YouTube movie, since I will set that later I can just pass null to it. The second parameter is if I want to use the chromeless player, in this case I set it to true. The chromeless player is usefull when you want the video player to have control that are similar to the rest of your application. It is also usefull when you want to put your video under a mask to escape the traditonnal square look of videos. If we continue with the code, after we created the MovieSprite, we have to wait for the player to be initialized to go on that’s why we put an event listener on the MovieSprite(youtubeMovie). Once the listener function is called, all that is left to do is call the loadVideoById method. Finding a video id from YouTube is really easy; if the url of the video you want to load looks like this:
http://www.youtube.com/watch?v=tprMEs-zfQA
Than your id is only the last part : “tprMEs-zfQA”.
Now if you want to control your video all you have to do is :
//this will pause the video youtubeMovie.pauseVideo() //this will make it play again youtubeMovie.playVideo() //to mute the video youtubeMovie.mute() //to set the volume to half of maximum youtubeMovie.setVolume(50) //to seek in the video to 20 seconds youtubeMovie.seekTo(20)
Well that is all it take to load a YouTube movie into Flash. I should warn you of some pitfalls; by reading the issues on the google code page, there seems to be problems with loading multiple videos at the same time. Also, destroying an instance of a MovieSprite seems to inhibit you from creating another one after so you should always keep an instance of you MovieSprite alive. Aside from that TubeLoc is an awesome library and I hope to see the proliferation of YouTube videos inside of Flash!




