1

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);

1 Answers1

0

As you mentioned, the start() and stop() methods' first argument is a timestamp based on a clock maintained audioContext.currentTime.

If the timestamp is less than current time, the start/stop method is executed immediately. Otherwise the methods are executed (oscillator is started or stopped respectively) when the clock is at the same time as the timestamp.

The when parameter describes at what time (in seconds) the sound should start playing. It is in the same time coordinate system as the AudioContext's currentTime attribute. If 0 is passed in for this value or if the value is less than currentTime, then the sound will start playing immediately. start may only be called one time and must be called before stop....

http://webaudio.github.io/web-audio-api/#widl-AudioBufferSourceNode-start-void-double-when-double-offset-double-duration

notthetup
  • 1,129
  • 9
  • 17