Skip to content

Instantly share code, notes, and snippets.

@Birch-san Birch-san/pluck.js

forked from kevincennis/pluck.js
Created May 6, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.