简体   繁体   English

网络音频振荡器为什么只播放一个音符一次?

[英]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. 当我使用Web音频振荡器(带有noteOn )成功创建了一个音调,然后调用了它的noteOff函数时,随后对noteOn调用不会再次播放该音调。 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))

Simply put - the API is designed that way, and optimised for that kind of use. 简而言之-API是按照这种方式设计的,并针对这种使用进行了优化。 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. 尽管可以创建振荡器池,但Web Audio API进行了优化,以至于不值得这样做。 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? 将频率更改为0怎么办? It seems to work in this Dataflow + Web Audio API sandbox. 它似乎可以在此Dataflow + Web Audio API沙箱中工作。 ( start and stop use the disconnect / reconnect pattern.) startstop使用断开/重新连接模式。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM