/****************************
****** Karplus-Strong *******
*****************************

ported from the gen~ example by thecharlie, 5/10/2106

Karplus-Strong is a simple physical model of a plucked
string. A burst of noise feeds very short delay line (with feedback) 
to acheieve the decaying sound. */

noteon = param( 'noteon', 0 )
freq   = param( 'frequency', 400 )
damp   = param( 'damping', .75 )
decay  = param( 'decay', .97 )
blend  = param( 'blend', .999 )
 
// create a line from 1 to 0 over 10 ms on trigger via noteon; 0 all other times
envelope = gtp( sub( 1, div( counter(1, 0, Infinity , noteon ), 441 ) ), 0 )
 
impulse = mul( noise(), envelope )
 
feedback = ssd()
 
d = delay( add( impulse, feedback.out ), div(44100,freq), { size:11025 } )
 
decayed = mul( d, t60( mul( decay, freq ) ) )
 
damped = feedback.in(
  mix( decayed, feedback.out, damp )
)
 
cb = play( damped )
 
let interval = setInterval( ()=> {
  cb.frequency = Math.floor( 220 + Math.random() * 440 )
  cb.noteon = 1
  setTimeout( ()=> { cb.noteon = 0 }, 10 )
}, 250 )
 
gui = new dat.GUI()
gui.add( cb, 'damping', 0,1 )
gui.add( cb, 'decay', 0, 4 )
gui.add( cb, 'blend', 0, 1 )
 
utilities.clear.callbacks.push( ()=> clearInterval( interval ) )