You want to keep a reference to the currently-playing sound. So that needs to be available outside the scope of playKick
. Then, within playKick
, you call stop
or noteOff
on the old sound before creating the new one and assigning it to that global var.
Something like:
var current;
$(document).on('keydown', function( e ) {
console.log(e);
switch (e.keyCode) {
case 81:
playKick(BUFFERS.kick);
break;
}
});
function playKick( instrument ) {
var source = context.createBufferSource();
source.buffer = instrument;
source.loop = true;
source.connect(context.destination);
if ( current ) {
if ( !current.stop ) {
current.stop = current.noteOff;
}
current.stop(0);
}
if ( !source.start ) {
source.start = source.noteOn;
}
source.start(0);
current = source;
}
Granted, there are certainly better ways to organize this — but hopefully this'll get you started.