mousine
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.SampleDataEvent;
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundMixer;
import flash.utils.ByteArray;
import flash.display.Graphics;
public class Mousine extends Sprite {
private static const SAMPLE_RATE:int = 44100;
private static const TWO_PI:Number = 2 * Math.PI;
private static const PLOT_HEIGHT:int = 200;
private static const CHANNEL_LENGTH:int = 256;
private var phase:Number;
private var freq:Number;
private var amp:Number;
private var snd:Sound;
private var newFreq:Number;
private var newAmp:Number;
public function Mousine() {
init();
}
private function init():void {
phase = 0;
freq = 440;
amp = 0.5;
newFreq = 440;
newAmp = 0.5;
snd = new Sound();
snd.addEventListener(SampleDataEvent.SAMPLE_DATA, sampleData);
snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function sampleData(event:SampleDataEvent):void {
var sample:Number;
visualize();
freq += (newFreq*2 - freq) * 0.02;
amp += (1.0-newAmp/stage.stageHeight - amp) * 0.1;
for(var i:int = 0; i < 2048; i++) {
phase += freq / SAMPLE_RATE;
if(phase > 1.0) {
phase--;
}
sample = sineWave(phase) * amp;
event.data.writeFloat(sample);
event.data.writeFloat(sample);
}
}
private function sineWave(phase:Number):Number {
return Math.sin(phase * TWO_PI);
}
private function onEnterFrame(event:Event):void {
newFreq = mouseX;
newAmp = mouseY;
}
private function visualize():void {
var bytes:ByteArray = new ByteArray();
SoundMixer.computeSpectrum(bytes, false, 0);
var g:Graphics = this.graphics;
g.clear();
g.lineStyle(0, 0xCCCCCC);
g.moveTo(0, PLOT_HEIGHT);
var n:Number = 0;
for (var i:int = 0; i < CHANNEL_LENGTH; i++) {
n = (bytes.readFloat() * PLOT_HEIGHT);
g.lineTo(i * 2, PLOT_HEIGHT - n);
}
g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);
g.lineStyle(0, 0x333333);
g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);
for (i = CHANNEL_LENGTH; i > 0; i--) {
n = (bytes.readFloat() * PLOT_HEIGHT);
g.lineTo(i * 2, PLOT_HEIGHT - n);
}
g.lineTo(0, PLOT_HEIGHT);
}
}
}