Visualization of Sound

The Flash plugin is required to view this object.

In actionscript 3, the new ComputeSpectrum method allows us to take a “snapshot” of the sound being played at a given time, and analyze its volume at different frequencies. This data is stored numerically in an array. We can then have flash visualize the sound by having it draw shapes based on the values in this array- in this case coloured rectangles.

In this example the audio file is lives in the library of the fla file. Often with flash audio visualization experiments the audio file is pulled in externally, however there are often security errors that can occur with this method. If you right click on the music file in the library and go to properties, you will see that its class is called MyMusicFile. This is the name which will be called upon from the code to pull it from the library.

Download .fla source file

Here is a copy of the code which is in the fla:

var s:Sound = new MyMusicFile() as Sound; // create instance of music in library
var myByteArray:ByteArray = new ByteArray(); // create bytearray
var song:SoundChannel = s.play(0,99); // play 99 times
var time:Timer = new Timer(50); // main timer ticks every 50 milliseconds
var gr:Sprite = new Sprite(); // sprite to contain all graphics
 
gr.x = 20;
gr.y = 200;
addChild(gr); // make graphics visible on stage
 
song.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
 
time.addEventListener(TimerEvent.TIMER, timerHandler);
time.start();
 
function soundCompleteHandler(event:Event):void {
	time.stop();
}
 
function timerHandler(event:TimerEvent):void {
 
	SoundMixer.computeSpectrum(myByteArray, true);   // take sound "snapshot"
 
	gr.graphics.clear(); // clear all previous drawn graphics
	gr.graphics.lineStyle(1, 0x000000);
	gr.graphics.beginFill(Math.random()*0xFFFFFF);
	gr.graphics.moveTo(0, 0);
 
	var w:uint = 10;
 
	for (var i:uint = 1; i < 512; i++) {    // loop through each array position
		var t:Number = myByteArray.readFloat(); // get volume of array position
		var h:Number = (t * 100);
		gr.graphics.drawRect(i, 0, w, -h); // create rectangle based on volume
	}
 
}

Other Resources:

Sound Spectrum Contest :: Many examples with source

Another ComputeSpectrum Example

This entry was posted in Actionscript, Intermediate, Tutorials and tagged . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*