Sound generator test
/**
* Copyright Pelisalinet ( http://wonderfl.net/user/Pelisalinet )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/e6VH
*/
package
{
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.SampleDataEvent;
import flash.events.TimerEvent;
import flash.media.Sound;
import flash.media.SoundMixer;
import flash.utils.ByteArray;
import flash.utils.Timer;
[SWF(width="465", height="465", backgroundColor="0xFFFFFF", frameRate="40")]
public class Main extends Sprite
{
private static const SAMPLING:int = 10048;
private static const SAMPLING_RATE:int = 22100;
private static const PI:Number = Math.PI * 4;
private static const VOLUME:Number = 0.5;
private static const MAX:Number = 9.0;
private var container:Array;
public function Main()
{
container = [];
var t:Timer = new Timer(400);
t.addEventListener(TimerEvent.TIMER, addSound);
t.start();
var sound:Sound = new Sound;
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleData);
sound.play();
addEventListener(Event.ENTER_FRAME, onFrame);
}
private function addSound(e:TimerEvent=null):void
{
var freq:Number = 220 * Math.pow(2, (int(30*Math.random()))/500);
var s:SoundData = new SoundData(freq, 0.05, 0.05, 40, 0.5);
container.push(s);
}
private function onSampleData(e:SampleDataEvent):void
{
var data:ByteArray = e.data;
var pos:Number = e.position;
var len:int = container.length;
var s:SoundData;
var i:int, n:int;
for(i=0 ; i<SAMPLING ; i++)
{
var d:Number = 0;
n = len;
while(n--)
{
s = container[n] as SoundData;
var w:Number = (PI * s.frequency / SAMPLING_RATE);
d += VOLUME * s.volume * Math.sin(((pos + i) * w) % PI) * 0.7;
}
d = (d > -MAX)?(d):(MAX);
d = (d < MAX)?(d):(MAX);
data.writeFloat(d);
data.writeFloat(d);
}
n = container.length;
while(n--)
{
s = (container[n] as SoundData);
s.renderSound();
if(s.state == 3) container.splice(n,1);
}
}
private function onFrame(e:Event):void {
var bytes:ByteArray = new ByteArray();
SoundMixer.computeSpectrum(bytes, true, 0);
for (var i:int = 0; i < 50; i++)
{
var spec:Number = bytes.readFloat();
var h:int = 250 * spec;
}
}
}
}
class SoundData
{
public var frequency:Number;
public var volume:Number;
public var state:int;
private var fadeIn:Number;
private var fadeOut:Number;
private var show:Number;
private var volMax:Number;
private var count:int;
public function SoundData(frequency:Number, fadeIn:Number, fadeOut:Number, show:int, volMax:Number)
{
this.frequency = frequency;
this.fadeIn = fadeIn;
this.fadeOut = fadeOut;
this.show = show;
this.volMax = volMax;
this.volume = this.state = this.count = 0;
}
public function renderSound():void
{
switch(state)
{
case 0:
volume += fadeIn;
if(volume>=volMax)
{
volume = volMax;
state = 1;
}
break;
case 1:
count ++;
if(count == show) state = 2;
break;
case 2:
volume -= fadeOut;
if(volume <= 0)
{
state = 3;
volume = 0;
}
break;
}
}
}