13.11. Setting the Volume of a Sound

Problem

You want to set the volume of a sound.

Solution

Use the setVolume( ) method of the Sound object that controls the sound.

Discussion

You can use Sound.setVolume( ) to set the volume on a scale of 0 to 100, in which 0 is mute and 100 is the loudest:

mySound_sound.setVolume(50);

It is possible to set the volume beyond the range of 0 to 100. If you set the volume to less than 0, Flash converts the volume setting to its absolute value. For example, if you set the volume to -50, Flash plays the sound at 50% volume (+50). If you exceed the value of 100, the sound gets increasingly distorted. The exception to this is if you are setting the volume of a parent Sound object in which the nested Sound objects’ volumes are less than 100. For example, if your nested Sound object has a volume of 50 and you set the parent Sound object to a volume of 200, the result is that the nested sound seems to play at full (100 percent) volume.

// Create two Sound objects. One targets the current timeline, and the other targets
// a nested timeline.
parent_sound = new Sound(this);
nested_sound = new Sound(this.soundHolder_mc);

// Attach a sound to the nested Sound object. nested_sound.attachSound("MySoundSymbol"); // Play the nested sound. nested_sound.start( ); // Set the volume of the nested sound to 50 and the volume of the parent sound to // 200. The result is that the nested sound seems to play at full volume. nested_sound.setVolume(50); parent_sound.setVolume(200); ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.