Skip to content

Instantly share code, notes, and snippets.

@kevincennis
Last active December 6, 2019 06:04
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kevincennis/6059128 to your computer and use it in GitHub Desktop.
Save kevincennis/6059128 to your computer and use it in GitHub Desktop.
Karplus-Strong with Web Audio API
function Pluck( ctx ) {
this.sr = ctx.sampleRate;
this.pro = ctx.createScriptProcessor( 512, 0, 1 );
this.pro.connect( ctx.destination );
}
Pluck.prototype.play = function( freq ) {
var N = Math.round( this.sr / freq ),
impulse = this.sr / 1000,
y = new Float32Array( N ),
n = 0;
this.pro.onaudioprocess = function( e ) {
var out = e.outputBuffer.getChannelData( 0 ), i = 0, xn;
for ( ; i < out.length; ++i ) {
xn = ( --impulse >= 0 ) ? Math.random() - 0.5 : 0;
out[ i ] = y[ n ] = xn + ( y[ n ] + y[ ( n + 1 ) % N ] ) / 2;
if ( ++n >= N || !this.playing ) {
n = 0;
}
}
}.bind( this );
this.playing = true;
};
Pluck.prototype.pause = function() {
this.playing = false;
};
// usage:
var ctx = new webkitAudioContext(),
pluck = new Pluck( ctx );
pluck.play( 220 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment