Simplifying Sounds in Actionscript 3

As I’ve been working on my latest game I’ve had to manage a number of sounds. I’ve got background music which must be looped and potentially swapped out for another song in certain situations. I have different effects that I want to be played at different times and usually only one at a time. Finally, I have a slow motion effect that causes the music to slow down or speed up. While implementing I’ve found Adobe’s sound library to be a pain to work with and Andre’s awesome pitch library has some limitations, so I wrote some convenient wrappers which I thought I’d share with you. Check out the source code and a quick example after the fold.

Example Use of the SoundFx class music from http://www.lucadebernardi.com

At a glance I’ve combined the sound channel and sound classes together to allow you to conveniently manage the sound instance. You can now loop the sound indefinitely (instead of a set number of times), stop, pause, and resume the sound directly. It would also be easy to extend my implementation to include other useful operations such as changing the sound’s volume — really anything that is currently managed by the channel.

I’ve also touched up Andre’s MP3Pitch class. Basically I wanted to be able to do the same things with it as I could with the SoundFx class I just outlined. It was especially important that I be able to loop the music, too. This meant listening for the SOUND_COMPLETE event, but Andre’s original implementation never fired that event because he filled the buffer with zero’s after the original track was finished. I’ve removed that part of the code and added the rest of the convenience methods I outlined above.

In both cases I have the classes extend from the Sound class. This way you can manage the sound asset in Flash directly, which is convenient for me. If you would rather load the sound either via the constructor or through a URL (as the MP3Pitch class did originally) that’s easy enough to change. If there’s interest I can even provide such an implementation.

Anyway, I hope the demo was interesting and you can find a use for these classes in your next project!

Leave A Comment