Tonejs / Tone.js

A Web Audio framework for making interactive music in the browser.
https://tonejs.github.io
MIT License
13.39k stars 976 forks source link

Extra latency in comparison to Web Audio Api #1108

Closed YoniH closed 2 years ago

YoniH commented 2 years ago

I had a feeling that tone.js adds extra latency on top of the standard web audio api, so I wrote a small app to test it:

https://yonih.github.io/latency-test/

You can find the code here.

At least in my setup (Mac M1, Chrome browser) the difference between plain Web Audio Api and Tone.js is very audiable and unacceptable.

I recorded myself playing with the test app, so I can look at the recording's waveform and measure exactly how much time it took between the keystroke sound and the time that the sample sound came out of the speakers. That is, the latency. Here is the recording.

And here are the results: Web audio api: 76ms 61ms 57ms Tone.js: 157ms. 162ms, 160ms

Am I missing something? Did I write the tone.js code wrong? Can I expect tone.js to respond as quickly as plain web audio api?

YoniH commented 2 years ago

Looking at the results, it seems that the difference is about 100ms, which is exactly the default lookahead. I did set the the lookahead to 0 though, and also called Tone.immediate(). Maybe I have a bug around that area?

marcelblum commented 2 years ago

You're right that the cause of the latency is lookAhead. But in your code you're creating your Players before instantiating a new audioContext with a lower lookAhead. That results in those players still using the older default Tone context with the higher lookAhead. You actually don't need to create a new context if all you want is to lower the lookAhead, that can be changed dynamically at any time Tone.getContext().lookAhead = 0.

YoniH commented 2 years ago

Yes, that was it 🎉🎉🎉 Now the latency I'm getting is similar to plain Web Audio Api. Thanks 😄