When I successfully create a tone with a Web Audio oscillator (with noteOn
), then call its noteOff
function, subsequent calls to noteOn
doesn't play the tone again. I seem to have to create a new oscillator to play a new note. Why is this?
var ctx = new webkitAudioContext();
var osc = ctx.createOscillator();
osc.connect(ctx.destination);
osc.start(0); // tone is heard (previously noteOn(0))
// ... some time later
osc.stop(0); // tone falls silent (previously noteOff(0))
// ... some time later
osc.start(0); // no effect! (previously noteOn(0))
When I successfully create a tone with a Web Audio oscillator (with noteOn
), then call its noteOff
function, subsequent calls to noteOn
doesn't play the tone again. I seem to have to create a new oscillator to play a new note. Why is this?
var ctx = new webkitAudioContext();
var osc = ctx.createOscillator();
osc.connect(ctx.destination);
osc.start(0); // tone is heard (previously noteOn(0))
// ... some time later
osc.stop(0); // tone falls silent (previously noteOff(0))
// ... some time later
osc.start(0); // no effect! (previously noteOn(0))
Share
Improve this question
edited Feb 1, 2013 at 0:27
aaaidan
asked Oct 27, 2012 at 0:32
aaaidanaaaidan
7,3268 gold badges68 silver badges106 bronze badges
3 Answers
Reset to default 9Simply put - the API is designed that way, and optimised for that kind of use. One doesn't have much choice except creating a new oscillator per note.
Use an oscillator pool and control note on/off with a gain node. Like analog synths, the oscillators are running all the time in the pool.
While it can work to create an oscillator pool, the Web Audio API has been so optimized that it's not worth doing. I previously thought an oscillator pool was a good idea, but it's not. It's quite simple to create a new oscillator every time you need a new note -- much simpler than maintaining a pool -- and there is no significant hit to performance caused by this continual create/garbage-collect process.
And if you think about it, this is a very clean programming model. No need to maintain references to objects and then reuse them later. Less state to maintain.
What about changing the frequency to 0? It seems to work in this Dataflow + Web Audio API sandbox. (start
and stop
use the disconnect / reconnect pattern.)