aaaidan
aaaidan

Reputation: 7316

why does a web audio oscillator only play a note once?

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))

Upvotes: 7

Views: 3529

Answers (3)

fisherwebdev
fisherwebdev

Reputation: 12690

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.

Upvotes: 6

forresto
forresto

Reputation: 12388

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.)

Upvotes: 5

Oskar Eriksson
Oskar Eriksson

Reputation: 2641

Simply 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.

Upvotes: 9

Related Questions