SoundMixer.computeSpectrum()

I was playing around with ActionScript 3.0’s new SoundMixer.computeSpectrum() method last night, and managed to build this simple example:

var url:String = "http://www.helpexamples.com/flash/sound/song3.mp3";
var request:URLRequest = new URLRequest(url);
var s:Sound = new Sound();
s.addEventListener(Event.COMPLETE, completeHandler);
s.load(request);
var song:SoundChannel = s.play();
song.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
var ba:ByteArray = new ByteArray();

var gr:Sprite = new Sprite();
gr.x = 20;
gr.y = 200;
addChild(gr);

var time:Timer = new Timer(50);
time.addEventListener(TimerEvent.TIMER, timerHandler);
time.start();

function completeHandler(event:Event):void {
event.target.play();
}
function soundCompleteHandler(event:Event):void {
time.stop();
}
function timerHandler(event:TimerEvent):void {
SoundMixer.computeSpectrum(ba, true);
var i:int;
gr.graphics.clear();
gr.graphics.lineStyle(0, 0xFF0000);
gr.graphics.beginFill(0xFF0000);
gr.graphics.moveTo(0, 0);
var w:uint = 2;
for (i=0; i<512; i+=w) {
var t:Number = ba.readFloat();
var n:Number = (t * 100);
gr.graphics.drawRect(i, 0, w, -n);
}
}

(** Sorry about the lack of formatting. I’m working on getting the blog restyled, and adding a bunch new AS2 and AS3 examples.)

UPDATE: Tom Green wrote a great article on the SoundMixer class over on Community MX, check it out: Sound Visualization in Flash CS3.