In the below code I expect to create a new Oscillator node assigned to o each time that the button element is pressed allowing for multiple presses resulting in multiple 1 second tones at 440. However what I am finding is that the button can only be pressed once to yield a tone, after that it goes dead as if I am not creating new Oscillator nodes. I'm bootstrapping into JavaScript and I suspect it must be something trivial. Anyone have an idea?
<html>
<body>
<button id='but' label='Button'/>
<script>
function secondContext(){
play([440],0,1);
}
function play(freqs, delay, duration) {
freqs.forEach(function(freq){
o = audio_context.createOscillator();
o.frequency.value = freq;
o.connect(audio_context.destination);
o.start(0);
o.stop(1);
});
}
var audio_context = new (AudioContext || webkitAudioContext);
button_ele = document.getElementById('but')
button_ele.addEventListener('click',function(){secondContext()});
</script>
</body>
</html>
EDIT:
Just found this question which addresses the issue. The solution is to add the audio_context.currentTime() to the offset like so:
o.start(audio_context.currentTime + 0);
o.stop(audio_context.currentTime + 1);