mohayonao / web-audio-engine

Pure JS implementation of the Web Audio API
243 stars 32 forks source link

Reduce CPU usage for StreamAudioContext. #56

Closed tustin2121 closed 7 years ago

tustin2121 commented 7 years ago

I had concerns that the the WAE was taking up 100% of my CPU usage when running. (Chrome's web audio doesn't seem to take up any CPU at all, but it's not nearly as flexible when it comes to audio buffers.)

I looked into the library and twiddled with some timings here. It seems calling setTimeout(0) means this function is being called far too often. I set the timeout all the way up to 1000ms and it doesn't disrupt the audio at all on my computer (probably due to the drain callback), while it does take node's CPU usage from 100% to under 15% usage. Setting it to 100ms seems to have all the benefits of easing off the CPU without the complaints about empty buffers.

(Tested on a mac using top in a Terminal window, using npm's speaker module as the output.)

tustin2121 commented 7 years ago

What is that test suite even testing? How many times it calls the function? That seems like a bad test to me. It should be testing throughput rather than how many times write is called... It's the constant calls to write that are being reduced here, to lessen CPU usage.

mohayonao commented 7 years ago

The WAE seems to use too much CPU, as you noticed.

But, it seems that sound is missing if use 100 msec loop, in my environment (MacBook Pro 2014 mid and play command)

$ cd web-auidio-engine/demo
$ npm install
$ node demo sines -o stdout | play -t s16 -r 44100 -c 2 -

I attempted with several parameters.

// CPU: 100%
setImmediate(renderingProcess);

// CPU: 0 - 5% (but the sound is missing)
setTimeout(renderingProcess, 100);  // or 10

// CPU: 20 - 25%
setTimeout(renderingProcess, 0);

I want to use 0 msec timeout loop instead. Can you chage the commit of your pull request?