Skip to content

Commit 515b366

Browse files
committed
Add ring buffer to p5.SoundFile AudioWorklet processor
1 parent 49ada2a commit 515b366

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed

src/audioWorklet/soundFileProcessor.js

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,29 @@
1-
// import processor name via preval.require so that it's available as a value at compile time
1+
// import dependencies via preval.require so that they're available as values at compile time
22
const processorNames = preval.require('./processorNames');
3+
const RingBuffer = preval.require('./ringBuffer').default;
34

45
class SoundFileProcessor extends AudioWorkletProcessor {
6+
constructor(options) {
7+
super();
8+
9+
const processorOptions = options.processorOptions || {};
10+
this.bufferSize = processorOptions.bufferSize || 256;
11+
this.inputRingBuffer = new RingBuffer(this.bufferSize, 1);
12+
this.inputRingBufferArraySequence = [new Float32Array(this.bufferSize)];
13+
}
14+
515
process(inputs) {
616
const input = inputs[0];
7-
const inputChannel = input[0];
8-
const position = inputChannel[inputChannel.length - 1] || 0;
17+
// we only care about the first input channel, because that contains the position data
18+
this.inputRingBuffer.push([input[0]]);
19+
20+
if (this.inputRingBuffer.framesAvailable >= this.bufferSize) {
21+
this.inputRingBuffer.pull(this.inputRingBufferArraySequence);
22+
const inputChannel = this.inputRingBufferArraySequence[0];
23+
const position = inputChannel[inputChannel.length - 1] || 0;
924

10-
this.port.postMessage({ name: 'position', position: position });
25+
this.port.postMessage({ name: 'position', position: position });
26+
}
1127

1228
return true;
1329
}

src/customAudioNode.js

Whitespace-only changes.

src/soundfile.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1243,7 +1243,9 @@ define(function (require) {
12431243
self._workletNode.disconnect();
12441244
delete self._workletNode;
12451245
}
1246-
self._workletNode = new AudioWorkletNode(ac, processorNames.soundFileProcessor);
1246+
self._workletNode = new AudioWorkletNode(ac, processorNames.soundFileProcessor, {
1247+
processorOptions: { bufferSize: 256 }
1248+
});
12471249
self._workletNode.port.onmessage = event => {
12481250
if (event.data.name === 'position') {
12491251
// event.data.position should only be 0 when paused

0 commit comments

Comments
 (0)