Sound fun and TEDx

I’ve been gearing up to perform/present at TEDx in Columbia SC on Monday. Super excited but still lots left to get done. So… I figured it might help keep the juices flowing if I shared some simple code fiddling related to what I’ll be doing there as a tiny teaser. I’ll post more after the event, if anyone is interested.


import flash.display.Shape;
import flash.display.Sprite;
import flash.events.SampleDataEvent;
import flash.events.MouseEvent;
import flash.media.Sound;
 
[SWF(width=550, height=400, backgroundColor=0x462300, frameRate=20)]
 
const TWICE_PI:Number = Math.PI * 2;
const BASE_KEY:uint = 32;
const NUM_KEYS:uint = 19;
 
var dot:Shape = new Shape();
var track:Sprite = new Sprite();
 
var keySize:Number = stage.stageHeight / NUM_KEYS;
var freq:Number;
var phase:Number = 0;
var gain:int = 0;
 
init();
 
function init():void {
	drawKeys();
 
	stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
	stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
 
	var sound:Sound = new Sound();
	sound.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleData);
	sound.play();
 
	dot.graphics.beginFill(0xff7070);
	dot.graphics.drawCircle(0, 0, 11);
	dot.x = stage.stageWidth * .5;
	addChild(track);
	track.addChild(dot);
	track.graphics.lineStyle(1, 0x90f070);
}
 
function drawKeys():void {
	graphics.lineStyle(0, 0x999999);
	for (var n:int; n < NUM_KEYS; ++n) {
		var m:uint = (BASE_KEY + NUM_KEYS - 1 - n) % 12;
		graphics.beginFill(m == 2 || m == 5 || m == 7 || m == 10 || m == 0 ? 0x333333 : 0xffffff);
		graphics.drawRect(0, keySize * n, stage.stageWidth, keySize);
	}
}
 
function getYFromKey(key:Number):int {
	return Math.round( stage.stageHeight - (keySize * (key - BASE_KEY)) - (keySize * .5) );
}
 
function mouseDownHandler(event:MouseEvent):void {
	gain = 1;
}
function mouseUpHandler(event:MouseEvent):void {
	gain = 0;
}
 
function onSampleData(event:SampleDataEvent):void {
	dot.y = mouseY;
	var keyNum:Number = (-dot.y + stage.stageHeight) / keySize + BASE_KEY - .5;
	var lastFreq:Number = freq;
	freq = 440 * Math.pow(2, (keyNum - 49) / 12);
	var deltaPhase:Number = freq/44100 * TWICE_PI;
    for (var i:int; i < 2048; i++) { // extra iterations helps reduce pops, but 2048 is minimum
		phase += deltaPhase;
		var sample:Number = Math.sin(phase) * gain;
        event.data.writeFloat(sample); // left
        event.data.writeFloat(sample); // right
    }
	dot.x++;
	track.x--;
 
	if (gain) {
		track.graphics.lineTo(dot.x, dot.y);
	} else {
		track.graphics.moveTo(dot.x, dot.y);
	}
}

One Response to “Sound fun and TEDx”

  1. intoxo poxed » Blog Archive » Yay random! Says:

    [...] and interrupted because I was terribly nervous about an upcoming few minutes on stage for a 1-off piece involving an audience-sound-driven game thing… a TEDx project I’ve been wrestling with. [...]

Leave a Reply