1

I am working on a project where I am currently trying to generate tone using audio context. Here is what I came up so far:

 $("#btn").click(function(){
    var context = new (window.AudioContext || window.webkitAudioContext)();
    var osc = context.createOscillator(); // instantiate an oscillator
    osc.type = 'sine'; // this is the default - also square, sawtooth, triangle
    osc.frequency.value = 440; // Hz
    osc.connect(context.destination); // connect it to the destination
    osc.start(); // start the oscillator
    osc.stop(context.currentTime + 1);
    })

I got the solution from stackoverflow. It perfectly makes the tone I am looking for. However, it only works for only less than six activation. In other words, when I click the button(with id === "btn") more than six times, it no longer makes the tone.

Here is jsFiddle.net link that has the same syntax as above click here

Can you help me fix the problem?

  • 1
    https://stackoverflow.com/questions/43511096/uncaught-domexception-failed-to-construct-audiocontext-the-number-of-hardwar and https://stackoverflow.com/questions/25046470/failed-to-construct-audiocontext-number-of-hardware-contexts-reached-maximum – Michael Coker Jul 01 '17 at 16:33

1 Answers1

1

You have to call context.close() after the osc.stop. But this is not so trivial because if you call it right after, it will not even play the audio because it's async.

A solution would be to put it inside a setTimeout:

// ...
osc.start();
osc.stop(context.currentTime + 1);
setTimeout(function () {
  osc.close();
}, 1000); // 1000 = 1s used at .stop

Alterantively, you could do both .stop. and .close inside setTimeout:

// ...
osc.start();
setTimeout(function () {
  osc.stop(); // note that there is no when argument, i.e. stop immetidately  
  osc.close();
}, 1000);

In my opinion, the second option is better since you don't have to match stop and timeout times.


The code example from the question, updated with the answer:

$("#one").click(function(){
  var context = new (window.AudioContext || window.webkitAudioContext)();
  var osc = context.createOscillator(); // instantiate an oscillator
  osc.type = 'sine'; // this is the default - also square, sawtooth, triangle
  osc.frequency.value = 440; // Hz
  osc.connect(context.destination); // connect it to the destination
  osc.start(); // start the oscillator
  setTimeout(function () {
    osc.stop();
    context.close();
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search">
<button id="one">
hello
</button>
Marko Gresak
  • 7,950
  • 5
  • 40
  • 46