网络音频 api 计时是否比 setTimeout 更精确

Is the web audio api timing more precise than setTimeout

在网络音频中推送声音时 api 您可以设置声音从 source.start(startTime); 开始的时间。但是我想知道那有多精确。我知道setTimeout()只是将要执行的代码放在事件队列中。我假设这也是网络音频 api 所做的,但这只是一个猜测。这样两者就没有区别了。

我尝试了运行一些漫长的运行过程才播放声音并且声音确实延迟了。

  //...
  source.start(startTime + 0.2);
  //....
 let i = 0;
 while( i < 100000){
   console.log("p" + i);
   i++;
 }

网络音频 api 在后台使用 setTimeout 也是如此。如果可以的话,我可以通过使用网络工作者来提高响应速度吗?我知道网络工作者可以访问 setTimeout,但我不确定它是否可以访问网络音频 api。

来自文档:

Audio workers provide the ability for direct scripted audio processing to be done inside a web worker context, and are defined by a couple of interfaces (new as of 29th August 2014.) These are not implemented in any browsers yet

这只涉及音频处理,我不确定是否只包括播放音频。

Is the web audio api timing more precise than setTimeout?

是的,到目前为止!音频计时器 implementation 寻求减少(累积)延迟并提供实时和精确的计时功能,直至采样级别。它使用音频事件的精确调度程序。

来自MDN

Timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. So applications such as drum machines and sequencers are well within reach.

来自the W3C Editor's Draft 20 December 2016

[...] In particular, instead of using message queue, implementors can use memory that is shared between threads, as long as the memory operations are not reordered.

setTimeout()的工作方式对于一般的音频处理来说不够准确,甚至可以限制其下限时间值(例如,将其设置为1ms可能会被浏览器更改为4ms)。它可能会或可能不会在目标时间触发,具体取决于事件队列以及其他因素。

要记住的另一件事是网络音频 API 中的所有预定时间都是相对于 AudioContextcurrentTime 的值(同上)。

So does the web audio api uses setTimeout under the hood?

有点已经回答了,但没有,绝对没有:)

Audio Worker 节点将用于处理音频数据(就像当前但已弃用的 ScriptProcessorNode),但在单独的线程上,而不是自己播放音频。所有音频播放都通过主音频线程进行。在 Audio Workers Nodes here.

上查看更多信息