12.5.09

AS3: Dynamically Loading Sounds in FlashDevelop

Dynamically Loading Sounds in FlashDevelop

Dynamically loading sounds in an AS3 movies allows you to store files seperately from your movie. Depending on where and how your sound is stored there may be significant time involved in loading it. Another method of using sound in your movie by embedding it directly into your movie can be found here.

The Set Up:

  • Either upload sound to your own webspace, or find the address to one online to use for testing. The sound must be formatted as a mp3 to be loaded into a movie.
  • Create a new AS3 project space in FlashDevelop.

Non-blocking image load:

  • ... Non-Blocking?:
    Loading an image without Blocking means that while the sound is being loaded, code continues to run. This is a problem if the application demands that the sound plays immediately when you call Sound.play(). However, blocking sound loading takes some foresight in AS3, and non-blocking sound loading is adequate for many situations. If you need your sound to play immediately when you call Sound.play() and are using this method, make sure you give your sound adequate time to load before calling play().

The Code:

   // entry point
var loadedSound:Sound = new Sound(new URLRequest("http://sites.google.com/site/programmingetc/Home/sploosh.mp3")); // Begin loading sound from the web
loadedSound.play(); // Sound will play after it has finished loading.
Line By Line:


  1. Lines up with the "//entry point" comment that should be in the default as3 project in FlashDevelop.
  2. Create a sound object. By providing it's constructor with a URLRequest, it will begin downloading the sound immediately, alternately you could call loadedSound.load(URLRequest).
  3. Play the sound. Techinically this queue's it up to be played once it is finished loading.

.zip source for this project can be found here

11.5.09

AS3: Embedding Sounds in FlashDevelop

Embedding Sounds in FlashDevelop


Embedding sounds in an AS3 movie will give fast access with no preloading. As an alternative, the same sounds can be used in multiple movies. In order to update sounds without rebuilding your project, or to save space by using the same images in multiple movies, you may want to also check out a tutorial on how to load sounds from an external source here.

The Set Up:
  • Get yourself a soundclip. Flash supports many types of embedded sound including:

  • AAC, AIFF, MP3, AVI, WAV, AU

  • Create a new AS3 project space in FlashDevelop.

  • Right click on your "src" folder, in the dropdown menu click "add >> new folder"

  • Change the name of your New Folder to snd.

  • Now add your soundclip to the project in one of two ways:

  • A) Find your soundclip in the windows filesystem and drag it directly into your project and drop it on your "snd" folder.

  • B) Right click the "snd" folder, click "add >> existing item", select the soundclip you want to add.

Note: Creating the "snd" folder is not necessary, it is just good to get in the habit of organizing your projects. Alternately you could just store everything directly in the "src" folder.


Getting your image in the movie:

  1. Add the Embed tag:
    You need to create an embed tag in order to make your soundclip accessible to the movie:
    [Embed(source='snd/sound.mp3')]
    "snd" corresponds to the folder the clip is stored in, and "sound.mp3" should be replaced with the name of your file.


  2. Create a class for the Embed tag:
    In order to use the embed tag, a class variable must be defined directly below it. This class variable is instantiated to create the embedded sound. The signature of a variable used for embedding can vary, the example below is a class variable and should be added after the opening brackets of your class, before any function definitions:
    [[Embed(source='snd/sound.mp3')]

    private const embeddedSound:Class;

  3. Create an instance an embedded sound:
    In order to create a useable object from a soundclip class, you simply create a new instance if the soundclip's class, and cast it to an instance of Sound. This code should go after the //entry point comment in your AS3 project.
    var soundClip:Sound = new embeddedSound(); // Create an instance of the embedded sound

  4. Play the sound:
    All that is left is to play the sound. This code can be inserted directly below the code from step 3:
    soundClip.play(); // Play the sound

.zip source for this project can be found here

AS3: Dynamically Loading Images in FlashDevelop

Dynamically Loading Images in FlashDevelop with AS3

Dynamically loading images in an AS3 movies allows you to store images seperately from your movie. Depending on where and how your image is stored there may be significant time involved in loading an image. Another method of using images in your movie by embedding them directly into your movie can be found here.

The Set Up:
  • Either upload an image do your own webspace, or find the address to one online to use for testing. The image must be formatted as a gif, jpg, or png.
  • Create a new AS3 project space in FlashDevelop.

Non-blocking image load:

  • ... Non-Blocking?:
    Loading an image without Blocking means that while the image is being loaded, code continues to run. This is a problem if the application demands that the image displays immediately after you call addChild(). However, blocking image loading takes some foresight in AS3, and non-blocking image loading is adequate for many situations. Blocking image loading will be covered in a future tutorial.

The Code:

// entry point
var imgInstance:Loader = new Loader(); // Create a new loader object
imgInstance.load(new URLRequest("http://sites.google.com/site/programmingetc/Home/image.png")); // Begin loading the image from web
addChild(imgInstance); // Display the image
Line By Line:

  1. Lines up with the "//entry point" comment that should be in the default as3 project in FlashDevelop.
  2. Create a loader object. It will be used to load the image, and can also be used as a DisplayObject for displaying the loaded image.
  3. Call the load method, with a URL parameter that points to an image (hosted on my google webspace).
  4. Add the loader instance to the sprite. The image will be displayed when it loads.

.zip source for this project can be found here

9.5.09

AS3: Embedding Images in FlashDevelop with AS3

Embedding Images in FlashDevelop with AS3

Embedding images in an AS3 movie will give faster access to images without preloading. As an alternative, the same images can be used in multiple movies. In order to update images without rebuilding your project, or save space by using the same images in multiple movies, you may want to also check out a tutorial on how to load images from an external source here.

The Set Up:

  • Get yourself an image. I haven't found a definite confirmation of formats supported for embedding anywhere, but from personal use I know "gif/jpg/png/svg" filetypes are supported. SVG is a vector graphic file, which I used Inkscape (a free open source vector art program) to create.
  • Create a new AS3 project space in FlashDevelop.
  • Right click on your "src" folder, in the dropdown menu click "add >> new folder"
  • Change the name of your New Folder to img.
  • Now add your image to the project in one of two ways:
  • A) Find your image in the windows filesystem and drag it directly into your project and drop it on your "img" folder.
  • B) Right click the "img" folder, click "add >> existing item", select the image you want to add.

Note: Creating the "img" folder is not necessary, it is just good to get in the habit of organizing your projects. Alternately you could just store everything directly in the "src" folder.

Getting your image in the movie:

  1. Add the Embed tag:
    FlashDevelop makes it easy to generate the necessary code to embed images. Place the typing cursor on an empty line above your main function. Next, in the Project View, right click on your image and click "Insert Into Document". FlashDevelop should add something like this at the cursor:
    [Embed(source='img/image.png')]
  2. Create a class for the Embed tag:
    In order to use the embed tag, a class variable must be defined directly below it. This class variable is instantiated to create the embedded image. The signature of a variable used for embedding can vary, the example below is a class variable and should be added after the opening brackets of your class, before any function definitions:
    [[Embed(source='img/image.png')]
    private const embeddedImage:Class;
  3. Create an instance an embedded image:
    In order to create a useable object from an image class, you simply create a new instance if the image class, and cast it to an instance of DisplayObject. This code should go after the //entry point comment in your AS3 project.
    // entry point
    var imgInstance:DisplayObject = new embeddedImage();
  4. Display the image:
    All that is left is to display the image. The position and rotation can be adjusted first, or they can be left to default (zero). This code can be inserted directly below the code from step 3:
       imgInstance.x = 50; // Set x coordinate of image
    imgInstance.y = 45; // Set y coordinate of image
    imgInstance.rotation = 45; // Set rotation to 45 degrees
    addChild(imgInstance); // Add this image to the Sprite object

.zip source for this project can be found here

4.5.09

AS3: Hello World Movie

First AS3 Movie: Hello World

This is a guide to making a quick Hello World app in FlashDevelop with ActionScript 3. This tutorial assumes you have FlashDevelop up and running, and a default ActionScript 3 project open, ready to build and run. If not check this tutorial for instructions on how to get there.

Building on the last tutorial, this is a very simple addition.



   // entry point
var textField:TextField = new TextField(); // Create a new TextField object
textField.text = "Hello World"; // Assign the text property of the field
addChild(textField); // Add the TextField to this Sprite

Breaking it down line by line:



  • Declaring and assigning a TextField:
       var textField:TextField = new TextField(); // Create a new TextField object
    This statement declares a TextField type variable named textField. The syntax for declaring a variable is: var variableName:variableType; Declaring a variable just tells the program to prepare for the existence of an object. If you try to do anything with an unassigned variable other than assign it to something, or check if the variable is null, you will get some kind of null object error. The way the variable is assigned above is just for convenience, it could also be done using:
       var textField:TextField; // Declare a new TextField variable
    textField = new TextField(); // Assign the variable to an object


  • Setting the text to be shown:
    textField.text = "Hello World";    // Assign the text property of the field

    This statement assigns the "text" property of the textField object to "Hello World". The "text" field contains the string that the TextField will draw to the stage. "Hello World" is surrounded by double quotes, which makes it a string in AS3.

  • Adding the TextField object to be drawn:
       addChild(textField);      // Add the TextField to this Sprite
    addChild(parameter) is a method that makes the object you used as a parameter a child of the drawable object that used the method. This means that textField is now a child of Main, and when Main draws, so will TextField (unless it's "visible" property is set to false). The class you are using extends the class "Sprite" so although you don't see the function addChild() defined anywhere in your code, it is a member of your class through its superclass.

  • Note:If you copy this instead of typing it in and using the autocomplete feature you will have to add this line up by your other imports to use the TextField:
    import flash.text.TextField;

Now build your project and run, you should now see the words "Hello World" in the top left corner of your window.

.zip source code for this project can be found here.

Tutorials on the Basics:
Embedding an Image
Dynamically loading an Image
Embedding and Playing Sound
Dynamically loading and Playing Sound

3.5.09

FlashDevelop: AS3 FlashDevelop Default AS3 Project

AS3 FlashDevelop Default AS3 Project

Time to explain what all that automatically created code in Main.as means. This tutorial assumes that you already have FlashDevelop up and running, and able to compile and run ActionScript 3. If you aren't at this point, check out my previous post.

This tutorial is really beginner programming info, If you already understand the code in Main.as, you can just scan, or skip to the next tutorial.

This is how Main.as looks initially:


package
{
import flash.display.Sprite;
import flash.events.Event;

/*
*
* ...
* @author your name
*/
public class Main extends Sprite
{

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);
// entry point
}

}

}



  • Basic syntax info:
    Blocks of code are opened and closed using { and }. The general format is "Statement { code; }". In AS3 blocks without a statement essentially do nothing because there is no block level scope for variables. If you don't what that means don't worry about it yet.

Breaking it down line by line:

    • Package:
      package
      You'll see this in all classes, it can be used for organizing your code. Unless you are planning on releasing your code to the public, or are creating an organized library for yourself, you can generally leave the package as is. One other point, your package must reflect your file system, so for example flash.display.Sprite would have to be in the path "..\src\flash\display\" and have the classname "Sprite".


    • Import:
       import flash.display.Sprite;
      import flash.events.Event;
      These statements make the Sprite class, and Event class accessible to your class. In flash you must import all of the classes you intend to use. You shouldn't have to worry about import too much because code completion in FlashDevelop automatically adds necessary import statements for you when you use it.


    • Documentation Comments:
       /*
      *
      * ...
      * @author your name
      */
      Commented lines. This is a specific type of comment meant to be used by a documentation generator. It is opened with /** and closed with */. If you type "@" on one of the comment lines, autocomplete will pop up and give you a bunch of tag options. These tags will be displayed in specific ways if you generate documentation. Even if you don't feel like setting up documentation for your class/project, it's still a good idea to put in a description of what the class is supposed to do where the "..." is to help you understand your code if you come back to it.


    • Declaring the class:
       public class Main extends Sprite
      This declares the class you are making. "public" means this class is accessible to any other class that wants to use it. "class" is a keyword labels the contents of the related code block as a class. Main is the name of your class. Quick side note about names, in AS3 public classes must be created inside files that match the name of the class, this is why our class "Main" is declared in the file "Main.as". If you screw this convention up, really it's ok because FlashDevelop gives you a nice descriptive error. "extends Sprite" declares this class as a subclass of Sprite. What this means is that our class will essentially be a Sprite, with whatever we code added to it. If you don't know about subclasses and inheritance yet, it might be wise to google "class inheritance" and "polymorphism".


    • Declaring a constructor:
        public function Main():void
    • This is the function that will be called when the Main class is used to create an object. Constructors will generally be declared public, unless you are making an abstract or static class, which isn't in the scope of this tutorial. function is a keyword that labels the related code block as a function. Main is the name of the function. In this case, the name must match the name of the class, which is what makes it a constructor in AS3. ( and ) are a space for parameters, but there are none to this constructor. Finally :void tells AS3 that this function does not return a value when called.


    • Class creation code:
      if (stage) init();
      else addEventListener(Event.ADDED_TO_STAGE, init);
    • This is an if-else statement. It first checks if this object's stage has been defined. This is somewhat like the _root of AS2, it is basically the main drawing area of a movie. If the stage exists in this object, then your code begins running the init() function. If not, addEventListener makes this class wait until it has been added to the stage, at which point it will call init. addEventListener arguments are the event time, and then the name of the method the event should call when it occurs.


    • Declaring an initialization function:
      private function init(e:Event = null):void
    • This function will be called either by the Main function, or the EventListener that the main function creates. It is private because it should only be called from within the Main class. The parameter e:Event = null declares a parameter named e, that is of the type Event. It is assigned to null which means that if you call init using init(); with no parameters, e will automatically be null. e is required to be there because functions called by event listeners will use the event parameter to report which event caused the function to be called. The :void means the function has no return value.


    • Coding an initialization function:
      removeEventListener(Event.ADDED_TO_STAGE, init);
    • This simply removes the event listener from this object if it was added in the constructor. This stops any potential problems of init being called by the handler again accidentally.

    • Code comments:
      // entry point
      Code comments start with a // and are terminated by a line end. They are just another way to document what your code does. Comments inside of code will not show up in documentation like the previously shown comments do.

    Final Comments:
    This default Main file works ideally for components that involve drawing. Using the init function and event listeners ensures that you don't attempt to do any drawing before your object is added to the stage. If your class doesn't require the stage you can just put your init code in the constructor and delete the init function.

    Next Tutorial, Hello World >>

    2.5.09

    FlashDevelop: Setting Up FlashDevelop for AS3 Programming

    Setting Up FlashDevelop for AS3 Programming:
    -Absolute beginner guide

    Hopefully this should be a straightforward tutorial of how to get FlashDevelop up and running your ActionScript 3 material... this tutorial was written on FlashDevelop 3.0 and Adobe Flex SDK 3.3.

    Files you need to grab:
    1. FlashDevelop at http://www.flashdevelop.org/community/viewforum.php?f=11 it's hosted in their forum I guess, not sure how long this link will be good.
    2. Adobe Flex SDK at http://www.adobe.com/products/flex/flexdownloads/ you can also get FlexBuilder from this site, I believe there is currently a month long trial before you have to buy. Lots of webpages say it is worth the money, but it's irrelevant to me because I will never have the money so I haven't tried it. Just grab the SDK if you are a cheap bastard like me.
    3. Windows Flash Player 9 or 10 Projector content debugger http://www.adobe.com/support/flashplayer/downloads.html this is optional, but you need some kind of Flash Player in order to run your movies, and this seems the best option to me because you have to deal with annoying security warnings etc if you use a Flash browser plugin to test. (The Projector is a standalone .exe).

    It doesn't matter what order you do the installations in for the current FlashDevelop (3.0) because the installer doesn't ask for any sort of SDK path.

    For SDK Install:

    1. Download the SDK http://www.adobe.com/products/flex/flexdownloads/
    2. Extract the SDK to a directory you will be able to find in the future. I went with "C:\AS3\flex_3.3.0.4852"
    3. Don't forget the location before you get FlashDevelop up and running.

    For FlashDevelop Install:

    1. Download the latest FlashDevelop http://www.flashdevelop.org/community/viewforum.php?f=11
    2. Run the installer (standard windows procedure for installing)
    3. Run the program.

    For Windows Flash Player 10 Projector content debugger install:

    1. Download the exe file from http://www.adobe.com/support/flashplayer/downloads.html
    2. Place the exe somewhere that you'll remember it. I stuck it in "C:\AS3\"

    Set Up ActionScript 3 IDE:

    1. Run FlashDevelop
    2. First you need to set your compile path, so that the SDK can compile your scripts. To do this go to Tools > Program Settings...
    3. A window titled Settings should pop up. You want to select AS3Context in the list on the left.
    4. Now in the right list under the Language category, there should be a property called "Flex SDK Location" set default to something like "c:\flex_sdk_3". You need to change this to the path where you unzipped all that Adobe Flex SDK stuff. You can open a folder browse window to make it easier by clicking on the "..." button that appears when you select "Flex SDK Location"
    5. Time to check if everything is set up correctly.

    Time to create an AS3 project and run it to see if everything is working:

    1. Click Project > New Project.
    2. Select AS3 Project in the Installed Templates List.
    3. Enter a Name for your Project
    4. This is a personal preference, but I always check "Create directory for project" because programming can quickly make a mess of your computer if you don't put atleast a little effort into organizing.
    5. If it isn't already selected, select the Project tab in the window on the right of your workspace.
    6. You should now see 3 folders: bin, lib, and src. bin will have some stuff in it to assist you in viewing/deploying your program that you don't really have to worry about right now. lib you can use later for your library files (if you use any). Currently we are concerned with the src folder. It should contain Main.as which you can double click to open in your editor window. There should be some basic framework code which I'll explain in the next tutorial, all you need to worry about now is checking if your setup works. Press F8 or click Project > Build Project To compile your empty project. The output should now flash a bunch of stuff and say "Build suceeded, Done (0)" at the end. If something else happens look at troubleshooting at the end of this blog.
    7. Now that your movie is built you can try to run it. You need to associate .swf files with the Flash Projector Debug program you downloaded earlier. In order to do this, expand your bin folder, and right click on a .swf file.
    8. Click Shell Menu... then Open With...
    9. Select the "Select a program from a list of installed programs" radio button and click OK.
    10. Click Browse... and find the Flash Projector exe file you downloaded.
    11. Check the "Always use the selected program to open this type of file box" and click OK.
    12. Now press F5 or click Project > Test Project to run your movie.
    13. The flash player you downloaded should now pop up and display a big white block. CONGRATULATIONS. Read on to the next tutorial to get yourself something a bit more impressive.

    Troubleshoot:

    Problem: When I try to build, a window pops up saying "Would you like to open the AS3 context settings to configure the compiler?"

    Solution: You probably forgot to set the Flex SDK Location property, or left it default. Check steps 2-4 under "Set Up ActionScript 3 IDE".

    Problem: When I press Test Program or hit F5 nothing happens.

    Solution: Check your output, does it say something about Execute not being related to any program? This means you didn't set up your file association correctly. Check steps 7-11 in the list right above troubleshooting.

    Explanation of the default AS3 project next >>