Sound frequencies animated!

Sunday, February 1, 2009


This was a really fun saturday afternoon project. I'd decided I needed a place to centralize my music. So I built my own xml driven glorified mp3 player. I made all the graphics myself. I made the background from a tutorial that I found at abduzeedo.com.



I created to external actionscript 3 classes for this:
  1. A class that manages each dynamic bubbles random animations
  2. A class that creates dynamic animations based on frequencies of a playing song, just like you see in winamp, or those fancy car stereos.
I learned the concept of this from
I'm really only going to talk about the latter here.
it takes two input params,
  1. An array containing, each slot containing a movieclip with a small blue rectangle in it. There can be any amount of these movieclips in the array. Each movieclip in the array represents a frequency in the sound animation.
  2. The maximum height that you want the bars to animate to at the peak level of audio.
Enough chatter, here's the code.

//here sound init documentation because I keep forgetting how to do it.
sound = new Sound();
sound.load(new URLRequest(mp3_path));
sound.play();

//to control the sound further, use a SoundChannel
var sch:SoundChannel; //this does not have a constructor

sch = sound.play();
//then use
sch.stop();
//and
sch = snd.play(sch.position);
//for the play and pause function


//Audio Animator Class
public class AudioAnimator extends MovieClip
{
private var ba:ByteArray = new ByteArray();
private var a:Number = 0;
private var f:Array;
private var maxH:Number = 0;
private var index:int = 0;

//s sound, f frequencies, mh maxHeight
public function AudioAnimator(frequencies:Array, mh:Number){
f = frequencies;
maxH = mh;
}

public function startAnimation(){
addEventListener(Event.ENTER_FRAME, freqs);
}

public function stopAnimation(){
removeEventListener(Event.ENTER_FRAME, freqs);
}

private function freqs(e:Event):void{
SoundMixer.computeSpectrum(ba,true,0);
index = 0;
for(var i=(256/(f.length)); i < 256; i+=(256/(f.length)))
{
a = ba.readFloat();
var num:Number = a*(a*maxH);
f[index].height = num;
index++;
}
}
}

I learned the concept from http://theflashblog.com/?p=181, but re-wrote a good part of it to fit my needs. The coolest part is that I've modularized it, and can now easily use it in any future project.

0 comments:

Post a Comment