Skip to content

Instantly share code, notes, and snippets.

@rndmcnlly
Created May 16, 2010 00:28
Show Gist options
  • Save rndmcnlly/402539 to your computer and use it in GitHub Desktop.
Save rndmcnlly/402539 to your computer and use it in GitHub Desktop.
var sys = require('sys');
var http = require('http');
var buffer = require('buffer');
var child_process = require('child_process');
var Buffer = buffer.Buffer;
var PORT = 8765;
var SAMPLE_RATE = 44100;
var CHUNK_SIZE = 4410; // why did I choose this??
function fix(x) { return ((2<<14)*x)|0; }
function hi(word) { return (word & 0xff00)>>8; }
function lo(word) { return word & 0xff; }
function radiansPerSample(freq) { return 2*Math.PI*freq/SAMPLE_RATE; }
function mtof(pitch) { return Math.pow(2.0, (pitch-69)/12.0)*440.0; }
var server = http.createServer(handle);
server.listen(PORT);
sys.puts('started on port '+PORT);
var lame = child_process.spawn('lame', ['-r','-m','m','-b','32','-','-']);
setInterval(render, 1000*CHUNK_SIZE/SAMPLE_RATE);
var bytes = new Buffer(2*CHUNK_SIZE); // 16-bit samples
var sample = 0;
function render() {
var pitch = Math.random()<0.25 ? 72 : (Math.random()<0.5?60:64);
var k = radiansPerSample(mtof(pitch));
for(var i = 0; i < CHUNK_SIZE; i++) {
sample++;
var fixed = fix(Math.sin(k*sample)>0?0.5:-0.5);
bytes[2*i+0] = lo(fixed);
bytes[2*i+1] = hi(fixed);
}
lame.stdin.write(bytes);
}
function handle(request, response) {
sys.puts('client connected from '+request.connection.remoteAddress);
response.writeHead(200, {'content-type': 'audio/mpeg'});
function send(data) { response.write(data); }
lame.stdout.addListener('data', send);
request.connection.addListener('end', function() {
sys.puts('client disconnected from '+request.connection.remoteAddress);
lame.stdout.removeListener('data', response.write);
response.end();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment