Reputation: 4578
I have a piece of code that looks something like below and it works fine. What it does is it launches an oscillator sound when the mouse clicks on a div named synth.It then stops playing the oscillator when the mouse button is released.
synth.onmousedown= function () {
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
};
synth.onmouseup = function () {
oscillator.disconnect();
};
I then added the code below so that when a user presses a keyboard charachter it triggers the oscillator. The problem is that when the key is held down it repeadedly plays and then won't stop when the keyboard character is released. I want to know if there are any libraries or code that can be used to circumvent this. The goal is to have the end result be like a mousedown/up effect but with keyboard movements triggering the sound.Thank you.
$('body').keydown(function() {
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
});
$('body').keyup(function() {
oscillator.disconnect();
});
Upvotes: 1
Views: 151
Reputation: 751
you could use underscore.js debounce if you need something fancier than the below option.
var keydown = false;
$('body').keydown(function() {
if(!keydown){
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
keydown = true;
}
});
$('body').keyup(function() {
oscillator.disconnect();
keydown = false;
});
Upvotes: 1
Reputation: 21830
This might be a workaround
var keyIsDown = false;
$('body').keydown(function() {
if(keyIsDown) {
// key is already down
return true;
}
keyIsDown = true;
// do your keydown handler
}
$('body').keyup(function() {
keyIsDown = false;
}
Upvotes: 0