最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why does a web audio oscillator only play a note once? - Stack Overflow

programmeradmin7浏览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))

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
Add a ment  | 

3 Answers 3

Reset to default 9

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.

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

发布评论

评论列表(0)

  1. 暂无评论