AS2 → AS3: Attaching Sounds From The Library

Download Example Files

AS3 no longer has an attachSound() method in the Sound object so attaching sounds from the library is a little different. It's actually more intuitive (as usual with AS3) because it acts just like attaching bitmaps and other objects out of the library.

The code to attach a sound from the library in AS2 is as follows:

Actionscript:
  1. var snd:Sound = new Sound();
  2. snd.attachSound("phone");
  3. snd.start();

Simple and quick, yes. But the AS3 code is even simpler and quicker:

Actionscript:
  1. var snd:Phone = new Phone();
  2. snd.play();

All we had to do was right-click our sound in the library and export it for ActionScript. We then gave it a class name of Phone and clicked OK. This allows me to just create a new Phone instance directly in my code and call play on it (not start, which made alot less sense) to run it. When you right-click and go to the properties you will see that once you select export for ActionScript the base class for our sound is populated as Sound. This ensures that the new class we create for the sound will inherit from the Sound class and Flash will automatically recognize it as a sound object under our new class name.

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

7 Comments

Simple but very useful.
Thanks, Matt, for all you do....

no problem Paul, glad i could help :P

Thanks... really... Am now migrating from AS2 habbits to AS3 and actually had found a lot sites with that theme but you really explain everything in cool easy exact way! Keep on like that!

someone has a crush

Hi this is all very well, but what if you are getting all your sound name out of an array as strings so that you can generate them dynamically eg

for ( var so in _sfxArr ){

var thisSound:String = _sfxArr[so];

var _tempSOUND:* = new this[ thisSound ](); // it's this bit I am unsure about ;(
_tempSOUND.play();

_soArr.push( _tempSOUND );

}

@Stephen: You can do something like this:

Actionscript:
  1. for (var so in _sfxArr)
  2. {
  3.     var ClassRef:Class = getDefinitionByName(_sfxArr[so]) as Class;
  4.    
  5.     var _tempSOUND:Sound = new ClassRef();
  6.     _tempSOUND.play();
  7.    
  8.     _soArr.push(_tempSOUND);
  9. }

Thanks... "Attaching Sound..." gets down to the "meat and potatoes" very fast. Just what I needed...

Leave a comment

(required)

(required)