All files / src music5000-worklet.js

0% Statements 0/0
0% Branches 0/0
0% Functions 0/0
0% Lines 0/0

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                                                                                         
/* global registerProcessor, AudioWorkletProcessor */
const BUFFER_SIZE = 65536;
 
registerProcessor(
    "music5000",
    class extends AudioWorkletProcessor {
        constructor() {
            super();
            this.port.onmessage = this.onmessage.bind(this);
 
            this.sampleBuffer = new Float32Array(BUFFER_SIZE);
            this.readPosition = 0;
            this.writePosition = 0;
        }
 
        onmessage(event) {
            // Receive a new 128-byte sample from the audio processor and write to the FIFO buffer
            const { data } = event;
            const sample = new Float32Array(data);
 
            if (this.writePosition === BUFFER_SIZE) {
                this.writePosition = 0;
            }
 
            for (let i = 0; i < data.length; i++) {
                this.sampleBuffer[this.writePosition++] = sample[i] / 32768.0; // Conversion to a range -1 to +1
            }
        }
 
        process(inputs, outputs) {
            // Playback
            if (this.readPosition === BUFFER_SIZE) {
                this.readPosition = 0;
            }
 
            for (let i = 0; i < outputs[0][0].length; i++) {
                outputs[0][0][i] = this.sampleBuffer[this.readPosition++];
                outputs[0][1][i] = this.sampleBuffer[this.readPosition++];
            }
 
            return true;
        }
    },
);