@@ -8,7 +8,8 @@ class ResamplerProcessor extends AudioWorkletProcessor {
88 this.ratio = this.inputSampleRate / this.outputSampleRate;
99 this.resampledBuffer = []; // Store resampled data to send to the main thread
1010 this.processCount = 0; //Counter.
11- this.port.postMessage({ type: 'log', data: "constructor" });
11+ this.pcmData = new Int16Array(8196);
12+ this.pcmIndex = 0;
1213 }
1314
1415 process(inputs, outputs, parameters) {
@@ -22,42 +23,44 @@ class ResamplerProcessor extends AudioWorkletProcessor {
2223 const inputChannel = input[0];
2324
2425 // Resample the data
25- const resampledData = this.resample(inputChannel);
26- this.resampledBuffer = this.resampledBuffer.concat(Array.from(resampledData));
26+ this.resample(inputChannel);
2727
2828 this.processCount++; //Increment process count
2929 let messageRate = 100; //Message sent every 100 process calls.
3030 // Send the resampled data to the main thread (send in chunks)
31- if (this.processCount % messageRate === 0 && this.resampledBuffer.length > 0) {
32- //Limit what we send.
33- let sendCount = 8196;
34- let send = this.resampledBuffer.slice(0, sendCount);
35-
36- this.port.postMessage({ type: 'resampledData', data: send }); //Send only part of the resampledBuffer;
37-
38- //Purge the buffer.
39- this.resampledBuffer = this.resampledBuffer.slice(sendCount);
31+ if (this.processCount % messageRate === 0 && this.pcmIndex > 0) {
32+ // Convert Int16Array to a binary buffer (ArrayBuffer)
33+ const pcmBuffer = new ArrayBuffer(this.pcmIndex * 2); // 2 bytes per sample
34+ const pcmView = new DataView(pcmBuffer);
35+ for (let i = 0; i < this.pcmIndex; i++) {
36+ const pcmData_i = this.pcmData[i];
37+ if (pcmData_i) {
38+ pcmView.setInt16(i * 2, pcmData_i, true); // true means little-endian
39+ }
40+ }
41+ this.port.postMessage({ type: 'resampledData', data: pcmBuffer });
42+ this.pcmData = new Int16Array(8196);
43+ this.pcmIndex = 0;
4044 }
4145
4246 return true;
4347 }
4448
4549 resample(inputChannel) {
46- const resampledData = [];
4750 let inputIndex = 0;
48-
49- for (let outputIndex = 0; outputIndex < inputChannel.length / this.ratio; outputIndex++) {
51+ const howMany = Math.floor(inputChannel.length / this.ratio)
52+ let outputIndex;
53+ for (outputIndex = 0; outputIndex < howMany; outputIndex++) {
5054 const inputIndexFloat = outputIndex * this.ratio;
5155 inputIndex = Math.floor(inputIndexFloat);
5256
5357 if (inputIndex < inputChannel.length) {
54- resampledData.push( inputChannel[inputIndex]); // Replace with interpolation
58+ this.pcmData[this.pcmIndex+outputIndex] = Math.max(-32768, Math.min(32767, inputChannel[inputIndex] * 32767));
5559 } else {
5660 break; //No more data, break out of loop
5761 }
5862 }
59-
60- return resampledData;
63+ this.pcmIndex += outputIndex;
6164 }
6265}
6366
0 commit comments