Monday, 10 August 2009

SoundMixer.computeSpectrum + Timeline Audio

I am posting this little Flash ActionScript hint here in case somebody googles the same problem...

When a sound is embedded directly in the timeline of a Flash movie as opposed to being loaded dynamically, using the SoundMixer.computeSpectrum() method doesn't work. Well, sometimes it does and sometimes it doesn't. I had a working sound visualiser when I went to bed last night, and this morning I didn't. No changes to the code at all.
After a lot of googling I found this post by Jason Van Cleave on the [Flashcoders] mailing list. Thanks Jason!

Basically you have to load in an mp3 of silence, assign it to a channel and play it. Then your spectrum analyzer will work with your intended sound/music.

I know - its weird!

I also found loads of posts about how it is not a true spectrum analyser yadder, yadder which were quite interesting. If you like that kind of thing...

// Strange silent mp3 hack
var s:Sound = new Sound(new URLRequest("2sec.mp3"));
var channel:SoundChannel = new SoundChannel();
channel =;

var ba:ByteArray = new ByteArray();
var g:Graphics =;
addEventListener(Event.ENTER_FRAME, loop);

function loop(e:Event):void
SoundMixer.computeSpectrum(ba, true, 4);
g.lineStyle(3, 0xFFFFFF, 1);
g.moveTo(0, 250);

for(var i:uint=0; i<256; i++)
var num:Number = -ba.readFloat() * 500;
g.drawRect(i*2, 250, 2, num/15);



No comments: