Question

Background:

I am currently trying to create a frequency visualizer for music using Flash and AS3 (for a variety of reasons). I am completely new to AS3, somewhat new to Flash, but have a bit of background with javascript, which has helped a lot to get me to where I am at. Anyway, I have this code that I have modified from a tutorial for creating bars for the amplitude of each range of frequency.

However, because I want it to work first I used probably the least efficient way of calculating each bar.

The Code:

import flash.media.Sound;
import flash.net.URLRequest;
import flash.events.Event;
import flash.utils.ByteArray;
import flash.display.FrameLabel;

var s:Sound = new Sound(new URLRequest("Mix 1 v4.mp3"));
s.play(0, 1);

var ba:ByteArray = new ByteArray();

addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event):void {
    graphics.clear();
    graphics.beginFill(0xFFFF00);
    graphics.drawRect(0, 502, 1280, 4);
    SoundMixer.computeSpectrum(ba, true);
    for (var i:uint=0; i<256; i+=8) {
        if (i<=8) {
        var num:Number = -ba.readFloat()*250;
        graphics.beginFill(0xFFFF00);
        graphics.drawRect(110, 500, 32, num);
        }
        if (i>8 && i<=16) {...

And the code continues increasing each if statement by 8 and each drawRect(110(34*x), 500...)

What I am looking for is a way to make the computeSpectrum and ByteArray "global" and have the graphics automatically drawn for each section of frequency values, instead of having 32 instances of if (i>32 && i<=40) {...

All in all, this code works. But it is most definitely not correct, at least from my limited experience (I imagine it will probably make some of you cringe.)

I realize there is probably a way to simplify it, but it is hard to figure out where to start, and is frustrating to debug when you don't know what you are doing (I'm sure we have all been there at one point)

I will work at coming up with my own solution, but I would be extremely happy with some guidance on this issue.

Thanks

Was it helpful?

Solution

This doesn't make sense:

for (var i:uint=0; i<256; i+=8) {
    if (i<=8) ...
    if (i>8 && i<=16) ...

You don't need the if statments, you know what i is on each go around the loop, so you can simplify this to:

for (var i:uint=0; i<256; i+=8)
{
    var index = (i / 8);//or bitshift using i >> 3
    var num:Number = -ba.readFloat()*250;
    graphics.beginFill(0xFFFF00);
    graphics.drawRect(110 + (index * 32), 500, 32, num);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top