Utilizing WebAudio for playing a sequence of musical notes has been quite successful. I have a playNote function that takes note frequency, start times, and stop times for each note as input. The parameters for generating the sequence are set prior to the actual audio playback, which can be a bit confusing. Essentially, this function creates an oscillator for each note - I've tried other methods, but this one is the most efficient.
However, I am facing an issue with stopping the sequence asynchronously (for example, when an external event occurs). I attempted to implement a master Gain node to control the output gating, but it seems like it needs to be placed "inside" the function in order to manipulate it later on. If I try to deactivate my gain object within the function itself, it's too late because the start and stop times have already been passed to the function.
Below is the code snippet for my function:
function playNote(audioContext,frequency, startTime, endTime, last) {
gainNode = audioContext.createGain(); //to achieve smooth rise/fall
oscillator = audioContext.createOscillator();
oscillator.frequency.value=frequency;
oscillator.connect(gainNode);
gainNode.connect(analyserScale); //analyser is a global variable
analyserScale.connect(audioContext.destination);
gainNode.gain.exponentialRampToValueAtTime(toneOn, startTime + trf);
gainNode.gain.exponentialRampToValueAtTime(toneOff, endTime+trf);
oscillator.start(startTime);
oscillator.stop(endTime);
}
Any assistance would be greatly appreciated!