How can I stop the web audio script processor and clear the buffer?

I am trying to figure out a way to stop the web audio script of a node processor without disabling it.

My initial thought was to simply set onaudioprocess to "null" to stop it, but when I do this, I hear a very short sound loop. I assume that the sound buffer is not cleared or something else, and it repeatedly plays the same buffer.

I tried some additional methods, for example, first setting the channel buffer array to 0, and then setting the "onaudioprocess" to "null", this still created a loop of sound instead of silence.

I have code like below (coffeescript)

context = new webkitAudioContext() scriptProcessor = context.createScriptProcessor() scriptProcessor.onaudioprocess = (e)-> outBufferL = e.outputBuffer.getChannelData(0) outBufferR = e.outputBuffer.getChannelData(1) i = 0 while i < bufferSize outBufferL[i] = randomNoiseFunc() outBufferR[i] = randomNoiseFunc() i++ return null return null 

Then when I want to stop him

 stopFunc1: -> scriptProcessor.onaudioprocess = null 

I also tried setting the buffer channel arrays to 0, and then setting the callback to zero

 stopFunc2: -> scriptProcessor.onaudioprocess = (e)-> outBufferL = e.outputBuffer.getChannelData(0) outBufferR = e.outputBuffer.getChannelData(1) i = 0 while i < bufferSize outBufferL[i] = 0 outBufferR[i] = 0 i++ scriptProcessor.onaudioprocess = null return null return null 

Both methods result in a piece of audio that works very quickly, and not without sound.

Is there a way to do it right or am I just thinking about it wrong?

Any help is greatly appreciated.

+6
source share
1 answer

Perhaps I misunderstand ...

But if you reject the onaudioprocess value, it will not stop playback immediately, unless you hit it at the very end of the current buffer.

Let's say your bufferSize is 2048, and you were unable to disable onaudioprocess halfway through the current buffer duration of 46 ms (2048/44100 * 1000). You will still have another 23 ms of audio that has already been processed by your ScriptProcessor before you turn it off.

The best bet is probably throwing the node gain into the path and just turning it off on demand.

+4
source

Source: https://habr.com/ru/post/949444/


All Articles