I want to create an oscillator that starts and stops when the user presses a key (just the space bar of now). But if the key is pressed for a too long, something like one second - the oscillator gets stuck and doesn't stop();
let signal = {}
class Beep {
constructor() {
this.audioCtx = new window.AudioContext();
this.osc = this.audioCtx.createOscillator();
this.gainNode = this.audioCtx.createGain();
this.gainNode.connect(this.audioCtx.destination);
this.osc.connect(this.gainNode);
signal.beep = this;
}
}
function startTransmission(e) {
if(e.keyCode == 32) {
let b = new Beep();
signal.beep.osc.start();
}
}
function stopTransmission(e) {
if(e.keyCode == 32) {
signal.beep.osc.stop();
}
}
document.body.onkeydown = (e) => startTransmission(e);
document.body.onkeyup = (e) => stopTransmission(e);
Found the solution if someone is interested... The problem is that the onKeyDown fires a new instance of the as long as it is pressed. So the function creates a new 'Beep' object ON TOP of the existing one. This way when the 'stopTransission' function is fired, it only stops the last oscillator, leaving the others beneath it running.
The way to overcome this is by creating a flag that toggles from 'false' to 'true' as soon as the first oscillator is created, and then does not permit the function to create more oscillators. That flag should be then reset to 'false' when the function is fired on key up.