Example : ActionScript 3 ComputeSpectrum

One of the cool new sound APIs in ActionScript 3, is the SoundMixer.computeSpectrum API. This allows you to get information about sounds currently playing within the player.

Andre Michelle put together a nice example that shows a visualization of the playing sound within the player. I tried to figure out the API from Andre Michelle’s example (some of it was over my head), but with some help from Grant Skinner at FITC, I finally figured it out and put together a simple example that shows how to use the API.


View the computeSpectrum Example (requires Flash Player 8.5 beta).Here is the code with comments.[code]package{import flash.display.Sprite;import flash.media.Sound;import flash.display.BitmapData;import flash.util.ByteArray;import flash.media.SoundMixer;import flash.events.Event;import flash.net.URLRequest;import flash.system.ApplicationDomain;public class SpectrumTest extends Sprite{private var bytes:ByteArray;private var CHANNEL_LENGTH:uint = 256;public function SpectrumTest(){var s:Sound = new Sound(new URLRequest("Helicopter.mp3"));s.play();bytes = new ByteArray();addEventListener( Event.ENTER_FRAME, onEnterFrame );}private function onEnterFrame( event: Event ): void{SoundMixer.computeSpectrum(bytes, true, 0);var smooth:Number;var value:Number;graphics.clear();//place in middle of screenvar xVal:Number = (stage.stageHeight / 2);//evenly distributevar spacing:Number = (stage.stageWidth / CHANNEL_LENGTH);var color:Number;//first 256 is left channell, second 256 is right channellfor(var i:int = 0; i < CHANNEL_LENGTH; i++){//get the next bytevalue = bytes.readFloat();//normalize it to be a value between 0 and 256value = (value * CHANNEL_LENGTH) << 0;//figure out the color based on the valuecolor = 0xFF0000|(value << 8);graphics.lineStyle(1, color, 1);graphics.beginFill(color);//draw the circle, position based on width and spectrum position//radius scaled down to fit bettergraphics.drawCircle(i * spacing, xVal, value / 8);}}}}[/code]Really cool stuff that opens up a ton of posibilities within Flash.Update : 05/08/06 : I have added the example to the labs subversion repository, so you can always find the most up-to-date version here.