Skip to content

Instantly share code, notes, and snippets.

@kirkbackus
Created May 14, 2016 13:05
Show Gist options
  • Save kirkbackus/41491ca3bc434294e056c346094ee98b to your computer and use it in GitHub Desktop.
Save kirkbackus/41491ca3bc434294e056c346094ee98b to your computer and use it in GitHub Desktop.
A simple implementation of a sine wave generator using the web-audio API
function Sine(ctx) {
this.sampleRate = ctx.sampleRate;
this.processor = ctx.createScriptProcessor(512,0,1)
this.processor.connect(ctx.destination);
this.offset = 0;
}
Sine.prototype.play = function(freq) {
this.processor.onaudioprocess = function(e) {
var out = e.outputBuffer.getChannelData(0);
var i=0;
for(; i<out.length; ++i) {
out[i] = Math.sin(2*Math.PI*freq*((this.offset+i)/this.sampleRate));
}
this.offset += i;
if (this.offset > this.sampleRate)
this.offset -= this.sampleRate;
}.bind(this);
this.playing = true;
}
@wrightwriter
Copy link

nvm, works, thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment