0

I am a student and am a beginner of Web APIs. I wrote this code for a practice of generating simple tones using JavaScript:

<html>
 <body>
  Frequency = <input type="number" id="freq"/><br>
  Waveform = <input type="text" id="wf"/><br>
  <button onclick="start()">Play</button>
  <button onclick="stop()">Stop</button>
 </body>
 <script>
  const context=new AudioContext();
  const oscillator=context.createOscillator();
  oscillator.type='sine';
  oscillator.frequency.value=400;
  const gain=context.createGain();
  oscillator.connect(gain);
  gain.connect(context.destination);
  function start()
  {
   oscillator.start();
  }
  function stop()
  {
   oscillator.stop();
  }
 </script>
</html>

The problem:

There are two buttons, Play and Stop. When I click on the Play button the tone is playing. Then I am clicking on the Stop button to stop the tone. Then, again when I am clicking on the Play button, no sound is heard!

What have I done wrong?

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Puspam
  • 2,137
  • 2
  • 12
  • 35
  • Looking at the console error that you receive the second time `.start` is called, I would assume this is related: https://stackoverflow.com/questions/32161832/web-audio-api-oscillator-node-error-cannot-call-start-more-than-once – Turnip Apr 18 '19 at 08:48
  • Thanks, that solved my issue. So, can I delete this question? – Puspam Apr 18 '19 at 09:05

1 Answers1

2

this is your solution:

 
$(document).ready(function() {
    var context = new AudioContext();
    var oscillator = context.createOscillator();   
    
    oscillator.start(); 
    $("#start").click(function() {
        if($('#freq').val()!=""){
          oscillator.frequency.value = $("#freq").val();
          console.log($("#freq").val());
        }else{
          oscillator.frequency.value = 400;
        }
        oscillator.connect(context.destination);
    });
    $("#stop").click(function() {
        oscillator.disconnect(context.destination);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
 <body>
  Frequency = <input type="number" id="freq"/><br>
  Waveform = <input type="text" id="wf"/><br>
  <button id="start">Play</button>
  <button id="stop">Stop</button>
 </body>
 
</html>
labu4bd
  • 693
  • 5
  • 13