25 Lines Piano

Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

A piano created with only 25 lines of actionscript 3. Uses real note frequencies, including 440A.

var frequency:Number = 55;
var nfArr:Array = new Array(55.00, 61.74, 65.41, 73.42, 82.41, 87.31, 98.00, 110.00, 123.47, 130.81, 146.83, 164.81, 174.61, 196.00, 220.00, 246.94, 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25, 587.33, 659.26, 698.46, 783.99, 880.00, 987.77, 58.27, 0, 69.30, 77.78, 0, 92.50, 103.83, 116.54, 0, 138.59, 155.56, 0, 185.00, 207.65, 233.08, 0, 277.18, 311.13, 0, 369.99, 415.30, 466.16, 0, 554.37, 622.25, 0, 739.99, 830.61, 932.33);
var tone:Sound = new Sound();
var amp: Number = 0;
var keyboard:MovieClip = addChild(new MovieClip())as MovieClip;
for (var i:int = 0; i<59; i++){
	var key:Sprite = keyboard.addChild(new Sprite()) as Sprite;
		key.graphics.beginFill(0xffffff);
		key.graphics.drawRect(i*30+2, 1, 28, 160);
	if(i>=30 && i==30 || i==32 || i==33 || i==35 || i==36 || i==37 || i==39 || i==40 || i==42 || i==43 || i==44 || i==46 || i==47 || i==49 || i==50 || i==51 || i==53 || i==54 || i==56 || i==57 || i==58){
		key.graphics.beginFill(0x000022);
		key.graphics.drawRect(30 * (i-29)-6.25, 0, 15, 100);}}
stage.addEventListener(MouseEvent.MOUSE_DOWN, function kDragOn(e:MouseEvent):void{keyboard.addEventListener(MouseEvent.MOUSE_OVER, kPlay)});
stage.addEventListener(MouseEvent.MOUSE_UP, function kDragOff(e:MouseEvent):void{keyboard.removeEventListener(MouseEvent.MOUSE_OVER, kPlay)});
keyboard.addEventListener(MouseEvent.MOUSE_DOWN, kPlay); 
function kPlay(e:MouseEvent):void{
	frequency = nfArr[keyboard.getChildIndex(Sprite(e.target))];
	amp = 2;}
addEventListener(Event.ENTER_FRAME, function dAmp(e:Event):void{amp = (amp > .05) ? amp-= 0.05 : 0;});
tone.addEventListener(SampleDataEvent.SAMPLE_DATA, sineWave);
function sineWave(e:SampleDataEvent):void {
	for (var i:int=0; i<2048; i++) {
        e.data.writeFloat(Math.sin((i+e.position) * 2*Math.PI/44100 * frequency) * amp);
        e.data.writeFloat(Math.sin((i+e.position) * 2*Math.PI/44100 * frequency) * amp);}}
tone.play();