Skip to content

Instantly share code, notes, and snippets.

@JKirchartz
Created September 17, 2014 19:06
Show Gist options
  • Save JKirchartz/f5251af72806ab5877eb to your computer and use it in GitHub Desktop.
Save JKirchartz/f5251af72806ab5877eb to your computer and use it in GitHub Desktop.
Chromatic Scales & sound synthesis in Actionscript
[SWF(width=200,height=50,backgroundColor=0x666666,frameRate=24)]
var sound:Sound = new Sound();
/* ################ Set the Starting Frequency */
var freq:Number=1046.5;
/* ################ Set the Sample Rate */
var rate:Number=44100;
var phase:Number=0;
var chan:SoundChannel = new SoundChannel();
var trans:SoundTransform = new SoundTransform(0,0);
chan.soundTransform = trans;
var tog=false;
var lab:TextField = new TextField();
var lab2:TextField = new TextField();
var format:TextFormat = new TextFormat();
lab.x=25;
lab2.x=70;
lab.y=lab2.y=20;
lab.text="Play";
lab.autoSize=TextFieldAutoSize.LEFT;
lab.background=true;
lab.border=true;
lab.backgroundColor=0xCC0000;
lab.selectable=lab2.selectable=false;
format.font="Verdana";
format.color=0xFF0000;
format.size=10;
lab2.defaultTextFormat=format;
addChild(lab);
addChild(lab2);
function togglePlay(event:MouseEvent) {
if (tog) {
lab.text="Play";
lab2.text="";
chan.stop();
freq=1046.5;
tog=false;
} else {
lab.text="Stop";
lab2.text="";
chan=sound.play();
tog=true;
}
}
lab.addEventListener(MouseEvent.CLICK, togglePlay);
function onSamplesCallback(event:SampleDataEvent):void {
for (var i:int = 0; i <8192; i++) {
phase+=freq/rate;
/* ################ Fourier Series for a Saw Wave */
var sample:Number = Math.sin(phase) + (.5 * Math.sin(2 * phase)) + (.33 * Math.sin(3 * phase)) + (.25 * Math.sin(4 * phase))+ (.2 * Math.sin(5 * phase)) + (.16 * Math.sin(6 * phase)) + (0.142857 * Math.sin(7 * phase));
event.data.writeFloat(sample * ((8192-i)/8192));
event.data.writeFloat(sample * ((8192-i)/8192));
}
/* ################ Randomise Freq up/down */
if (Math.round(Math.random()*100)%2==0) {
/* ################ Generate valid note frequencies */
if ((Math.round(freq)%2)==0) {
freq/=1.0594545;
} else {
freq/=1.0594756;
}
} else {
if ((Math.round(freq)%2)==0) {
freq*=1.0594545;
} else {
freq*=1.0594756;
}
}
/* ############## to get better sound, round freq to two decimals */
freq = (Math.round(freq *100)/100);
/* ############## Lets keep the sound in a range to protect eardrums */
if (freq<360||freq>2092.95) {
freq=1046.5;
}
lab2.text="Freq = "+freq.toString(10);
}
/* ################ If the channel is playing, keep creating sounds */
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, onSamplesCallback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment