Game Development Reference
Understanding the Sound Classes
Scripting sounds has gotten slightly more complicated in AS3
than it was in AS2. As with many aspects of AS3, the increased
complexity is matched by increased flexibility, but it can initially be
confusing. Objects of the Sound class are really just containers for
the actual sound data. When played, they generate a SoundChannel
object, and any subsequent commands should be issued to this
channel. As a result, you have to keep track of multiple objects to
have any level of control over the sound you trigger.
Another way in which sounds are handled differently is that
adjustable properties of sounds (like volume and panning) are no
longer individually assignable components. They are handled
through a new class known as the SoundTransform.Tosetthe
volume and pan of a sound, you need to change its channel
transform object. The following code starts a sound playing and
then creates a transform at 100% volume (1) and centered pan (0):
var soundChannel:SoundChannel = mySound.play();
soundChannel.soundTransform = new SoundTransform(1, 0);
The SoundEngine Class
ll create a class called SoundEngine that will manage playing all
the sounds in a game and take care of storing all the pertinent objects.
It will also provide us with easy methods to call for setting volume
and pan without having to, manually, create new transforms. One
other great feature it will afford us is the ability to call either internal
sounds (found in the library) or external sound files. It will follow
what is known as a Singleton design pattern, which you learned
about in Chapter 5. Suffice it to say that there will only be one
instance of the SoundEngine, and it will be accessible from anywhere.
This will make playing sounds as simple as a line or two of code.
CODE IMPROVES FROM USE
The version of the SoundEngine I created in the first edition of this topic
was a good starting place, but it was the first iteration of that code. I, sub-
sequently, started using it at my day job and encouraged others to do so
as well. Almost immediately we discovered limitations in it and potential
spots for bugs to arise. For a while, it became the most heavily edited
library in our workplace, often the butt of a joke:
must be the SoundEngine.
m pleased to say that thanks to the diligent
work of several amazing developers, I am presenting this new, improved
for this second edition. Most of the public interface
has stayed the same from the first version, so if you
ve been using it, you
should be able to easily replace your old files with this one without intro-
ducing any bugs. I
ll note in the coming pages any significant changes
between the two versions.