/*ByteBeater tiny library for playing bytebeat tunes in your browser via Web Audio API
* by Multiversum
* Usage: new ByteBeater(pattern_string), then call play() and pause() methods
* e.g.
* var bb = new ByteBeater("((t<<1)^((t<<18)+(t>>7)&t>>12))|t>>(4-(1^7&(t>>19)))|t>>7"); bb.play()
* pattern_string accepts a JS expression from single 't' parameter
* with the following functions specified without Math: sin, cos, tan, floor, ceil
* Supported browsers: latest desktop WebKits and Geckos (Chrome, Firefox)
* This library is public domain. Have fun!
*/
ByteBeater = function(pstring) {
this.x = 0;
var bb = this;
var AudioContext = window.AudioContext||window.webkitAudioContext||window.mozAudioContext;
this.pattern = eval("(function(t){return "+pstring.replace(/sin|cos|tan|floor|ceil/g,function(s){return "Math."+s})+"})");
this.context = new AudioContext();
var factor = ~~(this.context.sampleRate/8000);
this.node = this.context.createJavaScriptNode(1024,1,1);
this.node.onaudioprocess = function(e){
var data = e.outputBuffer.getChannelData(0);
for(var i=0;i<data.length;i++)
data[i]=!(i%factor)?((bb.pattern(bb.x++))&255)/255:data[i-1];
}
this.play = function(){this.node.connect(this.context.destination)}
this.pause = function(){this.node.disconnect()}
}