Recipe 15.14. Changing
the Volume or Pan of a Sound
Problem
You want to change the volume of a sound, making it
softer or louder, or set the pan (amount of left/right balance) of
a sound.
Solution
Create a new SoundTransform object, specifying
the volume at which you want the sound to play, or the amount and
direction of panning you want to apply. Pass this to the
soundTransform property of the SoundChannel object
associated with the sound you want to control.
Discussion
In previous versions of ActionScript, you could
set the volume and panning of a sound directly on the Sound
object itself. Now these aspects of the sound playback are
abstracted into the SoundTransform class.
A SoundChannel object has a
soundTransform property, which is an instance of the
SoundTransform class. To change a sound's volume or panning,
create a new SoundTransform object and set the desired
values. Next, set the SoundChannel's soundTransform
property to this new object. For example, the following sets the
sound volume to 50 percent:
var _sound:Sound = new Sound(new URLRequest("song.mp3"));
var channel:SoundChannel = _sound.play( );
var transform:SoundTransform = new SoundTransform( );
transform.volume = .5;
channel.soundTransform = transform;
As you can gather, the volume can range from 0.0
(silent) to 1.0 (full volume). Similarly, you can set the panning
of a sound:
var channel:SoundChannel = _sound.play( );
var transform:SoundTransform = new SoundTransform( );
transform.pan = -1.0;
channel.soundTransform = transform;
This sets the sound to play only in the left
speaker, as the values here can range from -1.0 (full left) to 1.0
(full right).
You can also pass the volume and pan amounts
straight to the SoundTransform's constructor, like so:
var channel:SoundChannel = _sound.play( );
var transform:SoundTransform = new SoundTransform(.5, -1.0);
channel.soundTransform = transform;
The first parameter is volume, and the second is
pan.
See Also
Recipe 15.13
|