package { import flash.display.Sprite; import flash.events.Event; import flash.utils.ByteArray; [SWF(width=400, height=300, backgroundColor=0x000000)] /** * Demonstrates how to visualize a playing sound file's raw sound wave * as a vertical column chart of 512 values. */ public class graphic_flex_image_effects_11_Flex_SoundWave extends Sprite { // the dimensions of the visualization private const WAVE_WIDTH:uint = 300; // this is actually half of the total height as it goes both positive and negative private const WAVE_HEIGHT:uint = 100; // the color of the columns private const WAVE_COLOR:uint = 0xFFFFFF; private var _soundController:graphic_flex_image_effects_11_Flex_SoundController; /** * Constructor. Loads the sound file using SoundController. */ public function graphic_flex_image_effects_11_Flex_SoundWave() { _soundController = new graphic_flex_image_effects_11_Flex_SoundController("graphic-flex-image-effects-11-assets-AlienInTheCaverns.mp3"); _soundController.addEventListener(Event.CHANGE, onSoundChange); } /** * Updates the column chart sound visualization with the current sound data. */ private function updateGraph():void { // returns the raw sound wave data of the sound playing var spectrumData:ByteArray = _soundController.getSoundSpectrum(false); graphics.clear(); graphics.beginFill(WAVE_COLOR); // how columns will be scaled horizontally to fit within the desired dimensions var ratio:Number = WAVE_WIDTH/512; var x:Number = (stage.stageWidth-WAVE_WIDTH)/2; // will center the chart vertically var y:Number = stage.stageHeight/2; var i:int = -1; var value:Number; while (++i < 512) { // the value is scaled vertically to fit within the desired dimensions value = Math.ceil(WAVE_HEIGHT*spectrumData.readFloat()); // draw the column in a negative direction so that is drawn "up" on the y axis graphics.drawRect(x+i*ratio, y, 1, -value); } } /** * Handler for when the sound changes (basically, an ENTER_FRAME while the sound is playing). * This calls updateGraph() to redraw column chart. * * @param event Event dispatched by SoundController. */ private function onSoundChange(event:Event):void { updateGraph(); } } }