Creating Impulse Using JavaScriptNode (Web Audio API)

I am working with a web audio API and I am trying to create a JavaScriptNode that outputs momentum. That is, I want a node that produces 1, followed by a whole bunch of zeros, and nothing more.

I thought the code below would be a reasonable way to do this. I initialize a variable called "timeForAnImpulse" to true and use this variable to trigger a pulse output on the sound callback. In the callback, I set the timeForAnImpulse value to false.

It seems that it should work, but it is not. Instead of a single pulse, I get a pulse train (1 at the beginning of each buffer). Any idea what I'm doing wrong?

<script type="text/javascript"> window.onload = init; function impulseNodeCB(evt){ if(timeForAnImpulse){ var buf = evt.outputBuffer.getChannelData(0); buf[0] = 1; timeForAnImpulse = false; } } var timeForAnImpulse = true; function init() { var context = new webkitAudioContext(); impulseNode = context.createJavaScriptNode(2048,0,1); impulseNode.onaudioprocess = impulseNodeCB; impulseNode.connect(context.destination); } </script> </head> 
+4
source share
1 answer

Ok, I get it!

I assumed that the output buffer evt.outputBuffer.getChannelData(0) was initialized with zeros at the beginning of each callback. This is not true. Instead, it saves its values ​​from its last call. Explicitly zeroing the buffer in the else clause solved the problem.

 <script type="text/javascript"> window.onload = init; function impulseNodeCB(evt){ if(timeForAnImpulse){ var buf = evt.outputBuffer.getChannelData(0); buf[0] = 1; timeForAnImpulse = false; } else { buf[0] = 0; } } var timeForAnImpulse = true; function init() { var context = new webkitAudioContext(); impulseNode = context.createJavaScriptNode(2048,0,1); impulseNode.onaudioprocess = impulseNodeCB; impulseNode.connect(context.destination); } </script> </head> 
+4
source

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


All Articles