Do you remember attachSound of Actionscript 2.0'
We could attach sounds from the library such as MovieClip even though they were mp3.
With Actionscript 3.0, the method attachSound has been removed (what a surprise you could think'), but no worry, it is still easy to use in runtime an mp3 file placed in our FLA's library.
After having seen how to assign a class to sounds in library , we will now see how to realise the same thing but without the need to create a class for each sound. Very useful if you would find yourself with hundreds of sounds in library.
Let's see' I create a FLA and save it as 'main.fla'.
I import 10 different mp3 files to the library. In these examples, I use vocal sounds and I recommend you to use short sounds for testing purpose such as sound effects for buttons.
For each one of them, I assign a class the following way:
- right click the file in library and selection the property 'linkage'
- in the new opened window, select the option 'export for Actionscript' and in the text field Class, add 'Sound0'
- click OK. Flash will say that the assigned class has not been found and it will create one if accepted. We click OK once again.
We will go through the same process for all the 9 remaining sounds, assigning the class name Sound1, Sound2, Sound3'etc'etc
I drag on stage 10 instances of a button and assign them instance names such as button_0_btn, button_1_btn, button_2_btn'etc'etc.
I now create the Document Class, an AS file saved as 'Main.as', implemented the following way:
Code:
package
{
import flash.display.MovieClip;
import flash.utils.getDefinitionByName;
import flash.media.Sound;
import flash.events.MouseEvent;
public class Main extends MovieClip
{
public function Main()
{
initLabels();
}
private function initLabels():void
{
for( var i:int=0;i < 10;i++)
{
var b:*=this.getChildAt(i);
var button:Button=b;
button.label='Sound'+i;
button.addEventListener(MouseEvent.CLICK,playSound);
}
}
private function playSound(m:MouseEvent):void
{
var className:Class=getDefinitionByName(m.currentTarget.label)as Class;
var sound:Sound=new className();
sound.play();
}
}
}
The result:
Lets' analyse the code
Methods
initLabels();
using a cycle, I retrieve all the buttons placed on stage, assign a label name and assign a listener to the event CLICK which will call the method playSound
for( var i:int=0;i < 10;i++)
{
var b:*=this.getChildAt(i);
var button:Button=b;
button.label='Sound'+i;
button.addEventListener(MouseEvent.CLICK,playSound );
}
playSound();
using the getDefinitionByName Class I impost the label name of the button (m.currentTarget which caused the event, meaning the button clicked) as the Class name to be called
var className:Class=getDefinitionByName(m.currentTarge t.label) as Class;
I create an instance of that class which extends the Sound Class as we added it to the linkage
var sound:className=new className();
I start the sound
sound.play();
Stay tuned!
Bookmarks