Calculating Spectrum Data : MP3 « Development « Flash / Flex / ActionScript






Calculating Spectrum Data

 
package {
    import flash.utils.ByteArray;
    import flash.events.*;
    import flash.net.*;
    import flash.display.*;
    import flash.media.*;
    import flash.geom.*;

    public class Main extends Sprite {
        private const SPECTRUM_WIDTH:int = 256;

        private const BMP_HEIGHT:int = 200;
        private const BMP_WIDTH:int = 256;

        private var sound:Sound = new Sound(new URLRequest("http://www.java2s.com/y.mp3"));

        private var soundData:ByteArray;

        private var bitmapData:BitmapData;
        private var bitmapDisplay:Bitmap;

        public function Main () {
            sound.play();

            bitmapData = new BitmapData(BMP_WIDTH, BMP_HEIGHT, true, 0x00000000);
            bitmapDisplay = new Bitmap(bitmapData);
            addChild(bitmapDisplay);

            this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        public function onEnterFrame (event:Event):void {
            soundData = new ByteArray();
            SoundMixer.computeSpectrum(soundData);

            bitmapData.fillRect(bitmapData.rect, 0xFF000000);

            for (var i:int=0; i < SPECTRUM_WIDTH; i++) {
                var amplitude:Number = soundData.readFloat();

                var ampHeight:Number = BMP_HEIGHT/2 * (amplitude + 1);

                var rect:Rectangle = new Rectangle(i, BMP_HEIGHT -ampHeight, 1, ampHeight);
                bitmapData.fillRect(rect, 0xffffffff);
            }
        }
    }
}

        








Related examples in the same category

1.Load mp3 sound file
2.Load mp3 file from a URL
3.Find Out When a Sound Finishes Playing
4.Tracking the Progress of a Playing Sound
5.Reading the Level of a Sound
6.ID3 Reader