Previous Page
Next Page

Recipe 15.11. Reading the Level of a Sound

Problem

You want to know how loud a currently playing sound is.

Solution

Access the SoundChannel.leftPeak and SoundChannel.rightPeak properties.

Discussion

Any sound, as it is playing, goes through various levels of loudness and softness. This is known as its amplitude. ActionScript 3.0 lets you access the amplitude for the left and right channels of a stereo sound separately. These are the leftPeak and rightPeak properties of the SoundChannel object that is created when you start playing a sound.

These values are in a range from 0.0 to 1.0, with 1.0 being the maximum amplitude. Don't confuse this with volume, which can be an overall setting for a sound, and is controlled via the SoundTransorm object (see Recipe 15.14). This is the level of sound volume at a particular instance, and it varies constantly as the sound plays.

The following example reads these values and creates two bars, the lengths of which are based on the current amplitude of each channel on each frame:

package {
    import flash.display.Sprite;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.net.URLRequest;
    import flash.events.Event;
    
    public class SoundLevels extends Sprite {
        private var _sound:Sound;
        private var _channel:SoundChannel;
        
        public function SoundLevels(  ) {
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
            _sound = new Sound(new URLRequest("song.mp3"));
            _channel = _sound.play(  );
        }
        
        public function onEnterFrame(event:Event):void
        {
            var leftLevel:Number = _channel.leftPeak * 100;
            var rightLevel:Number = _channel.rightPeak * 100;
            graphics.clear(  );
            graphics.beginFill(0xcccccc);
            graphics.drawRect(10, 10, leftLevel, 10);
            graphics.endFill(  );
            graphics.beginFill(0xcccccc);
            graphics.drawRect(10, 25, rightLevel, 10);
            graphics.endFill(  );
            
        }       
    }
}

See Also

Recipe 15.1 for information on how to load external sound files and Recipe 15.14.


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)