-
-
Save lplume/dd49834a349006477c77da3f3637bb7f to your computer and use it in GitHub Desktop.
Karplus-Strong with Web Audio API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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