Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Web Audio API) Oscillator node error: cannot call start more than once

When I start my oscillator, stop it, and then start it again; I get the following error:

Uncaught InvalidStateError: Failed to execute 'start' on 'OscillatorNode': cannot call start more than once. 

Obviously I could use gain to "stop" the audio but that strikes me as poor practice. What's a more efficient way of stopping the oscillator while being able to start it again?

code (jsfiddle)

var ctx = new AudioContext(); var osc = ctx.createOscillator();  osc.frequency.value = 8000;  osc.connect(ctx.destination);  function startOsc(bool) {     if(bool === undefined) bool = true;          if(bool === true) {         osc.start(ctx.currentTime);     } else {         osc.stop(ctx.currentTime);     } }  $(document).ready(function() {     $("#start").click(function() {        startOsc();      });     $("#stop").click(function() {        startOsc(false);      }); }); 

Current solution (at time of question): http://jsfiddle.net/xbqbzgt2/2/

Final solution: http://jsfiddle.net/xbqbzgt2/3/

like image 888
Jacksonkr Avatar asked Aug 22 '15 23:08

Jacksonkr


2 Answers

A better way would be to start the oscillatorNode once and connect/disconnect the oscillatorNode from the graph when needed, ie :

var ctx = new AudioContext(); var osc = ctx.createOscillator();    osc.frequency.value = 8000;     osc.start();     $(document).ready(function() {     $("#start").click(function() {          osc.connect(ctx.destination);     });     $("#stop").click(function() {          osc.disconnect(ctx.destination);     }); }); 

This how muting in done in muting the thermin (mozilla web audio api documentation)

like image 82
Alice Oualouest Avatar answered Sep 28 '22 13:09

Alice Oualouest


The best solution I've found so far is to keep the SAME audioContext while recreating the oscillator every time you need to use it.

http://jsfiddle.net/xbqbzgt2/3/

FYI You can only create 6 audioContext objects per browser page lifespan (or at least per my hardware):

Uncaught NotSupportedError: Failed to construct 'AudioContext': The number of hardware contexts provided (6) is greater than or equal to the maximum bound (6). 
like image 38
Jacksonkr Avatar answered Sep 28 '22 15:09

Jacksonkr