Flash ActionScript(AS) Expert

Loading an external SWF file

Posted by: sarapeter on: May 3, 2009

Loading an external SWF file

In ActionScript 3.0, SWF files are loaded using the Loader class. To load an external SWF file, your ActionScript needs to do four things:

  1. Create a new URLRequest object with the url of the file.
  2. Create a new Loader object.
  3. Call the Loader object’s load() method, passing the URLRequest instance as a parameter.
  4. Call the addChild() method on a display object container (such as the main timeline of a Flash document) to add the Loader instance to the display list.

Ultimately, the code looks like this:

var request:URLRequest = new URLRequest("http://www.[yourdomain].com/externalSwf.swf");
var loader:Loader = new Loader()
loader.load(request);
addChild(loader);

This same code can be used to load an external image file such as a JPEG, GIF, or PNG image, by specifying the image file’s url rather than a SWF file’s url. A SWF file, unlike an image file, may contain ActionScript. Thus, although the process of loading a SWF file may be identical to loading an image, when loading an external SWF file both the SWF file doing the loading and the SWF file being loaded must reside in the same security sandbox if you plan to use ActionScript to communicate in any way to the external SWF file. Additionally, if the external SWF file contains classes that share the same namespace as classes in the loading SWF file, you may need to create a new application domain for the loaded SWF file in order to avoid namespace conflicts. For more information on security and application domain considerations, see Using the ApplicationDomain class and Loading SWF files and images.

When the external SWF file is successfully loaded, it can be accessed through the Loader.content property. If the external SWF file is published for ActionScript 3.0, this will be either a movie clip or a sprite, depending on which class it extends.

Considerations for loading an older SWF file

If the external SWF file has been published with an older version of ActionScript, there are important limitations to consider. Unlike an ActionScript 3.0 SWF file that runs in AVM2 (ActionScript Virtual Machine 2), a SWF file published for ActionScript 1.0 or 2.0 runs in AVM1 (ActionScript Virtual Machine 1).

When an AVM1 SWF file is successfully loaded, the loaded object (the Loader.content property) will be an AVM1Movie object. An AVM1Movie instance is not the same as a MovieClip instance. It is a display object, but unlike a movie clip, it does not include timeline-related methods or properties. The parent AVM2 SWF file will not have access to the properties, methods, or objects of the loaded AVM1Movie object.

There are additional restrictions on an AVM1 SWF file loaded by an AVM2 SWF file. For details, see the AVM1Movie class listing in the ActionScript 3.0 Language and Components Reference.

Loading an External .swf in AS3

Posted by: sarapeter on: May 3, 2009

Loading an External .swf in AS3

Here’s a simple example of loading a .swf in AS3. I had a typo before but now it’s fixed – sorry about that. Also, I updated it so you don’t have to strictly use it in an Class setting.

Happy Coding…

import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.Event;
import flash.events.ProgressEvent;

function startLoad()
{
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest(“MouseActions.swf”);
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
mLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressHandler);
mLoader.load(mRequest);
}

function onCompleteHandler(loadEvent:Event)
{
        addChild(loadEvent.currentTarget.content);
}
function onProgressHandler(mProgress:ProgressEvent)
{
var percent:Number = mProgress.bytesLoaded/mProgress.bytesTotal;
trace(percent);
}
startLoad();

[AS 3] Loading External .mp3 File and Retrieving ID3 Information

I just discovered that Actionscript 3 has the ability to read the data that some .mp3 files have in them. To demonstrate I created a little movie below that will output all this data and dump it in a TextArea Component. In addition, I created a little analyzer demo for the right and left channels.

First I needed a mask for the analyzer, so I used my Rectangle.as class.

  1. package   
  2. {   
  3.     import flash.display.Sprite;   
  4.     public class Rectangle extends Sprite   
  5.     {   
  6.         private var xPos:Number;   
  7.         private var yPos:Number;   
  8.         private var rWidth:Number;   
  9.         private var rHeight:Number;   
  10.         private var color:uint;   
  11.   
  12.         public function Rectangle(xPos:Number=0,yPos:Number=0,rWidth:Number=10,rHeight:Number=10,color:uint=0×336699)   
  13.         {   
  14.             this.graphics.beginFill(color);   
  15.             this.graphics.drawRect(xPos,yPos,rWidth,rHeight);   
  16.             this.graphics.endFill();   
  17.         }   
  18.     }   
  19. }  

Here is the document class

  1. package   
  2. {   
  3.     import flash.display.Sprite;   
  4.     import flash.display.Loader;   
  5.     import flash.media.*   
  6.     import flash.net.URLRequest;   
  7.     import flash.events.IOErrorEvent;   
  8.     import flash.events.ProgressEvent;   
  9.     import flash.events.Event;   
  10.     import flash.events.MouseEvent;   
  11.     import flash.text.*;   
  12.   
  13.     public class LoadSound extends Sprite   
  14.     {   
  15.         private var snd:Sound;   
  16.         private var sndChannel:SoundChannel;   
  17.         private var output:TextField;   
  18.         private var id3Array:Array;   
  19.         private var ct:uint;   
  20.   
  21.         private var image1:Loader = new Loader();   
  22.         private var image2:Loader = new Loader();   
  23.   
  24.         private var mask1:Rectangle;   
  25.         private var mask2:Rectangle;   
  26.   
  27.         public function LoadSound()   
  28.         {   
  29.             showInstructions();   
  30.             showGraphics();   
  31.             init();   
  32.         }   
  33.   
  34.         private function init():void  
  35.         {   
  36.             var snd:Sound = new Sound();   
  37.             snd.load(new URLRequest(“/path/to/mp3/file/”));   
  38.   
  39.             snd.addEventListener(IOErrorEvent.IO_ERROR, sndIOError);   
  40.             snd.addEventListener(ProgressEvent.PROGRESS, sndProgress);   
  41.             snd.addEventListener(Event.COMPLETE, sndComplete);   
  42.             snd.addEventListener(Event.ID3, ID3content);   
  43.   
  44.         }   
  45.   
  46.         private function sndIOError(e:IOErrorEvent):void  
  47.         {   
  48.             output.text = “An error occured when laoding the sound”;   
  49.         }   
  50.   
  51.         private function sndProgress(e:ProgressEvent):void  
  52.         {   
  53.             output.text = “Loading: ” + Math.round(100 * e.bytesLoaded / e.bytesTotal);   
  54.         }   
  55.   
  56.         private function sndComplete(e:Event):void  
  57.         {   
  58.             output.text = “Sound loaded - click the stage to play and stop”;   
  59.   
  60.             stage.addEventListener(MouseEvent.MOUSE_DOWN, toggleMusic);   
  61.   
  62.             var music:Sound = e.target as Sound;   
  63.   
  64.             function toggleMusic():void  
  65.             {   
  66.                 ct++;   
  67.   
  68.                 if (ct%2)   
  69.                 {   
  70.                     sndChannel = music.play();   
  71.                     addEventListener(Event.ENTER_FRAME, playSpectrum);   
  72.                 }   
  73.                 else  
  74.                 {   
  75.                     sndChannel.stop();   
  76.                     removeEventListener(Event.ENTER_FRAME, playSpectrum);   
  77.                 }   
  78.             }   
  79.         }   
  80.   
  81.         private function ID3content(e:Event):void  
  82.         {   
  83.             var id3Prop:ID3Info = e.target.id3;   
  84.   
  85.             var id3Array:Array = new Array();   
  86.   
  87.             for (var idName:String in id3Prop)   
  88.             {   
  89.                 //trace (“ID3 Tag”,idName, ”=”, id3Prop [idName]);   
  90.                 id3Array.push(new Array(idName, id3Prop [idName]));   
  91.             }   
  92.   
  93.             id3Text.text = “”;   
  94.   
  95.             for (var h:Number=0; h < id3Array.length; h++)   
  96.             {   
  97.                 // id3Text is the name of the TextArea component I placed on the stage in the .fla movie   
  98.                 // I also set the parameters for the componenet in the .fla movie   
  99.                 id3Text.text += id3Array[h][0] + “ = ” + id3Array[h][1] + “\n”;   
  100.             }   
  101.         }   
  102.   
  103.         private function playSpectrum(e:Event):void  
  104.         {   
  105.             mask1.y = sndChannel.leftPeak * -100;   
  106.             mask2.y = sndChannel.rightPeak * -100;   
  107.         }   
  108.   
  109.         private function showInstructions():void  
  110.         {   
  111.             // Small Black Text Formatting   
  112.             var insText:TextFormat = new TextFormat();   
  113.             insText.font = “Arial”;   
  114.             insText.color = 0xffffff;   
  115.             insText.size = 12;   
  116.             insText.underline = false;   
  117.   
  118.             // output TextField   
  119.             output = new TextField();   
  120.             output.defaultTextFormat = insText;   
  121.             addChild(output);   
  122.             output.x = 10;   
  123.             output.y = 35;   
  124.             output.width = stage.stageWidth;   
  125.             output.height = 22;   
  126.         }   
  127.   
  128.         private function showGraphics():void  
  129.         {   
  130.             image1.load(new URLRequest(“http://manewc.com/projects/flash/LoadSoundID3/gradient.jpg”));   
  131.             addChild(image1);   
  132.             image1.x = 10;   
  133.             image1.y = 200;   
  134.   
  135.             image2.load(new URLRequest(“http://manewc.com/projects/flash/LoadSoundID3/gradient2.jpg”));   
  136.             addChild(image2);   
  137.             image2.x = stage.stageWidth - 244;   
  138.             image2.y = 200;   
  139.   
  140.             // create an object to act as our mask   
  141.             mask1 = new Rectangle(image1.x, image1.y + 99, 100, 100);   
  142.             addChild(mask1);   
  143.   
  144.             mask2 = new Rectangle(image2.x, image2.y + 99, 100, 100);   
  145.             addChild(mask2);   
  146.   
  147.             // set the masks:   
  148.             image1.mask = mask1;   
  149.             image2.mask = mask2;   
  150.         }   
  151.     }   

AS2>>AS3: Loading & Playing External Sounds

Posted by: sarapeter on: May 1, 2009

AS2 → AS3: Loading & Playing External Sounds

Download Example Files

Loading and playing external sounds in AS3 is not far off from its AS2 counterpart. The code, as usual in AS3, is a little different because of the new event model, but really boils down to the same thing.

Let’s take a look at the AS2 version:

Actionscript:

  1. var s:Sound = new Sound();
  2.  
  3. s.onLoad = function():Void
  4. {
  5.     trace(“Song loaded.”);
  6. };
  7.  
  8. s.onSoundComplete = function():Void
  9. {
  10.     trace(“Song done.”);
  11. };
  12.  
  13. s.loadSound(“music.mp3″, true);

 

And here is how to do that in AS3:

Actionscript:

  1. var s:Sound = new Sound(new URLRequest(“music.mp3″));
  2. s.addEventListener(Event.COMPLETE, doLoadComplete);
  3.  
  4. var channel:SoundChannel = new SoundChannel();
  5. channel = s.play();
  6. channel.addEventListener(Event.SOUND_COMPLETE, doSoundComplete);
  7.  
  8. function doLoadComplete($evt:Event):void
  9. {
  10.     trace(“Song loaded.”);
  11. }
  12.  
  13. function doSoundComplete($evt:Event):void
  14. {
  15.     trace(“Song done.”);
  16. }

 

As you may have noticed, there is a strange work-around in AS3 for what used to be the onSoundComplete event. I did a bit of Googling before posting this and found an interesting post by Andre Michelle on the topic. That didn’t really solve my problem though, as I wanted to demonstrate how to do it in AS3, so I looked at the Flex reference for the AS2 to AS3 conversion of the onSoundComplete event and saw that it was replaced by, according to this, the soundComplete event in flash.media.SoundChannel. I went ahead and tried it out and it seemed to fire off fine on my machine, so here you have it.

Initially I had thought that the following lines of code would do the trick, but they didn’t:

Actionscript:

  1. var s:Sound = new Sound(new URLRequest(“music.mp3″));
  2. s.addEventListener(Event.COMPLETE, doLoadComplete);
  3. s.addEventListener(Event.SOUND_COMPLETE, doSoundComplete);
  4. s.play();

 

Hence why I Googled and tried what I did above, which, as I’ve already stated, seemed to fix the problem. I’m no expert on sound in Flash but if it works, why question it? :P

NOTE: I’ve obviously removed the “music.mp3″ file from the download so just grab any .mp3 you have, put it in the same folder that the example files are in, and rename it to music.mp3.

Flash Action Script 3 MP3 Player

Posted by: sarapeter on: May 1, 2009

Flash Action Script 3 MP3 Player:

Here goes Flash Action Script 3 MP3 PlayerPart 1. Need Your comments and support on the articles.

I am writing this first version of Flash Action Script 3 MP3 for beginners so that they can have an idea of Flash Action Script 3 Sound Classes. Also this code uses memory optimization techniques to reduce memory leaks.

To Learn More About Memory Optimization read my previous post

http://actionscript-blog.imaginationdev.com/Memory-Optimization-Flash-Action-Script-3

Flash Action Script 3 MP3 Player can be developed in 2 ways. 1- Songs are played once they are completely downloaded on the local machine, Part 1 of my Flash Action Script 3 MP3 Player uses this techniques. this approach is suitable when developing a desktop application. 2- Songs are buffered and streamed from the server and played simultaneously. This type of approach is common for Online Flash Action Script 3 MP3 Player. Part 2 of this article series will cover the 2nd methodology.

Building a Flash Action Script 3 MP3 Player is really easy using Flash Action Script 3 classes. Once you have the concepts of Sound class, SoundChannel class and Timer class in Flash Action Script 3 you are ready to develop a Media Player in Flash Action Script 3. In case you need guidance and help in the above mentioned classes you are welcome to leave comments and i will respond as soon as possible.

This might not be the best Flash Action Script 3 MP3 Player. This sure will guide you how to develop a Flash Action Script 3 MP3 Player using flash action script. There are number of flash media players available on the internet but very few i saw focussed on the fact that action script sound class has some problems when optimizing memory space. So i thought to write one sample of my own.

This flash MP3 player is easily customizable and reusable. In coming future i plan to write a Flash MP3 Player Component using Action Script3. Hopefully that article will also cover the basis of creating a flash component.

You can use the flash action script 3 Mp3 player code to build your own customized Flash Action Script 3 MP3 Players. Basic idea will always remain the same.

Flash Action Script 3 MP3 Player development starts with the code for loading XML and inserting data in the play list.

///////////////////////////////////////////////////////////////// //Loading XML /////////////////////////////////////////////////////////////////

var xmlData:XML; var xmlLoader:URLLoader = new URLLoader();xmlLoader.addEventListener(Event.COMPLETE, LoadXML);

xmlLoader.load(new URLRequest("playlist.xml"));
function LoadXML(e:Event):void {
 trace(LoadXML); xmlData = new XML(e.target.data);function getValues(input:XML) {
 var xmlCategoryList:XMLList = input.children(); var item:XML;var intCount:int = 0;

for each (item in xmlCategoryList) {
 playList.addItem({label:item.title, data:item.url}); intCount = intCount + 1;
}
}//end of get Values Function
getValues(xmlData);
}// end of Load XML

After that we will wait until user clicks on any song in play list. For handling play list event we will write the following code.

///////////////////////////////////////////////////////////////// //Play List Handler Function /////////////////////////////////////////////////////////////////

playList.addEventListener(Event.CHANGE, playListChangeHandler);
function playListChangeHandler(event:Event) {
if (flagSoundChannel==1) {
 soundChannel.stop();
} else if (flagSoundChannel==0) {
 flagSoundChannel=1;
} playSound(event.target.selectedItem.data);timeSlider.value=0;
}// end of change Handler

Above code calls another important function playSound. This method loads the new sound in the sound Object.

///////////////////////////////////////////////////////////////// //Play Sound Function /////////////////////////////////////////////////////////////////

function playSound(path) {
 songPath.url = path;if(playerObject.sound!=null)
 delete playerObject.sound;
playerObject.sound = new Sound();
addSoundEvents();
playerObject.sound.load(songPath);
}

Above code requires sound events to be handled before a new sound object is created. If you focus on the delete playerObject.sound; statement, this deletes the previous allocation of memory for the sound object. If we don’t do this a lot of memory will leak and eventually application will crash.

///////////////////////////////////////////////////////////////// //Sound Loading Event Handler Function /////////////////////////////////////////////////////////////////

function addSoundEvents():void
{
    playerObject.sound.addEventListener(Event.COMPLETE, funcSoundLoaded);
    playerObject.sound.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    playerObject.sound.addEventListener(ProgressEvent.PROGRESS,funcOnLoadProgress);
}
function funcSoundLoaded(event:Event) {
    var soundObject:Sound = event.target as Sound;
    var totalSoundDuration:Number;
    soundChannel=soundObject.play();
    totalSoundDuration=(soundObject.length/1000)/(60);
    totalSoundDuration=Math.floor((totalSoundDuration*100));
    totalSoundDuration=totalSoundDuration/100;
    timeSlider.maximum=(soundObject.length/1000);
    sliderDivisionValue=totalSoundDuration;
    fileTimeInSec = Math.floor(playerObject.sound.length/1000);
    secTimer.start();
}//end of Function Loaded
function funcOnLoadProgress(event:ProgressEvent):void {
    var loadedPct:uint =Math.round(100 * (event.bytesLoaded / event.bytesTotal));
    trace("The playerObject.sound is " + loadedPct + "% loaded.");
}
function onIOError(e:IOErrorEvent) {
    trace("The playerObject.sound can not be Loaded"+ e.text);
}

Above code implementation of sound event handlers. Lastly we will add Timers and GUI element event handlers. ///////////////////////////////////////////////////////////////// //Control Handlers UIDesign /////////////////////////////////////////////////////////////////

btnStop.addEventListener(MouseEvent.CLICK,funcStop);
btnPause.addEventListener(MouseEvent.CLICK,funcPause);
btnPlay.addEventListener(MouseEvent.CLICK,funcPlay);
btnForward.addEventListener(MouseEvent.CLICK,funcForward);
btnBack.addEventListener(MouseEvent.CLICK,funcReverse);
soundChannel.addEventListener(Event.SOUND_COMPLETE, funcComplete);
function funcComplete(event:Event) {
    soundChannel.stop();
    timeSlider.value=0;
    currPosition=0;
}
function funcStop(event:Event) {
    secTimer.reset();
    timeSlider.value=0;
    currPosition=0;
    soundChannel.stop();
    flagSoundChannel=0;
}
function funcPause(event:Event) {
    secTimer.stop();
    currPosition= soundChannel.position;
    soundChannel.stop();
    btnPlay.visible=true;
    btnPause.visible=false;
}
function funcPlay(event:Event) {
    soundChannel.stop();
    soundChannel=playerObject.sound.play(currPosition);
    btnPlay.visible=false;
    btnPause.visible=true;
    secTimer.start();
}
function funcForward(event:Event) {
    if (soundChannel.position+forwardDuration<=playerObject.sound.bytesTotal) {
        timeSlider.value+=forwardDuration/1000;
        soundChannel.stop();
        soundChannel=playerObject.sound.play(soundChannel.position+forwardDuration);
    }
    else
    {
        timeSlider.value=0;
        currPosition=0;
        soundChannel.stop();
        flagSoundChannel=0;
    }
}
function funcReverse(event:Event) {
    if (soundChannel.position-forwardDuration>0) {
        timeSlider.value-=forwardDuration/1000;
        soundChannel.stop();
        soundChannel=playerObject.sound.play(soundChannel.position-forwardDuration);
    }
    else
    {
        timeSlider.value=0;
        currPosition=0;
        soundChannel.stop();
        flagSoundChannel=0;
    }
}

///////////////////////////////////////////////////////////////// //Control Handlers Sliders /////////////////////////////////////////////////////////////////

timeSlider.addEventListener(SliderEvent.THUMB_PRESS,sliderPressed);
timeSlider.addEventListener(SliderEvent.THUMB_RELEASE,sliderReleased);
timeSlider.addEventListener(SliderEvent.CHANGE,sliderChangeHandler);
timeSlider.liveDragging =true;
function sliderChangeHandler(event:SliderEvent) {
    secTimer.stop();
    soundChannel.stop();
    soundChannel=playerObject.sound.play(event.target.value*1000);
    secTimer.start();
}
function sliderPressed(event:SliderEvent) {
}
function sliderReleased(event:SliderEvent) {
    secTimer.stop();
    soundChannel.stop();
    soundChannel=playerObject.sound.play(event.target.value*1000);
    secTimer.start();
}

///////////////////////////////////////////////////////////////// //Control Handlers Timers /////////////////////////////////////////////////////////////////

secTimer.addEventListener(TimerEvent.TIMER, onTick);
secTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
function onTick(event:TimerEvent):void {
    trace("Timer is running");
    timeSlider.value+=1;
}
function onTimerComplete(event:TimerEvent):void {
    trace("Time's Up!");
}

For Further details on voice control and sound buffering you may contact me. I will soon be writing part 2 of the flash MP3 Player series with voice control and Sound Buffering.

Kindly Let me know about your remarks if this article is being helpful in solving your problem.

Download Sample Project : Flash MP3 Player Using Action Script 3

Hello world!

Posted by: sarapeter on: May 1, 2009

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!