Search code examples
javascriptweb-audio-api

Web Audio-Stopping Oscillator Sound


Trying to create a pulsing tone. Found some help from another posting here (web audio api plays beep, beep,... beep at different rate). Needed to adapt the script. Came up with a satisfactory result that plays and pulses a tone. Cannot figure out a function to stop the tone: .stop() used with oscillators doesn't work.

Any help appreciated.

Here's my code:

<html>
<body>
<button id = "start1" onclick='tone();'>Play</button>
<button id = "stop1" onclick='stopper();'>Stop</button>
<script>
function tone(){
var context = new AudioContext();
var abc = context.createOscillator();
abc.frequency.value = 325;
var xyz = context.createOscillator();
xyz.type='sine';
xyz.frequency.value = 10;
var gain = context.createGain();
var ramp = context.createGain();
abc.connect(gain);
gain.connect(context.destination);
xyz.connect(ramp); 
ramp.gain.value = 0.3;
gain.gain.value = 0.3;
ramp.connect(gain.gain);
abc.start(0);
xyz.start(0);
}
function stopper()
{
abc.stop();
xyz.stop();
}
</script>
</body>
</html>


Solution

  • Moving comment to answer:

    The AudioAPI is not the problem, it's a simple variable scoping problem.

    Variables created in a function are not accessible outside that function, and the stopper() function can't access the abc/xyz variables.

    <html>
    <body>
    <button id = "start1" onclick='tone();'>Play</button>
    <button id = "stop1" onclick='stopper();'>Stop</button>
    <script>
    let context = null;
    let abc, xyz;
    
    function tone(){
        context = new AudioContext();
        abc = context.createOscillator();
        abc.frequency.value = 325;
        xyz = context.createOscillator();
        xyz.type='sine';
        xyz.frequency.value = 10;
        var gain = context.createGain();
        var ramp = context.createGain();
        abc.connect(gain);
        gain.connect(context.destination);
        xyz.connect(ramp); 
        ramp.gain.value = 0.3;
        gain.gain.value = 0.3;
        ramp.connect(gain.gain);
        abc.start(0);
        xyz.start(0);
    }
    function stopper()
    {
        abc?.stop();
        xyz?.stop();
    }
    </script>
    </body>
    </html>