jevstrudel.git / packages / supradough / dough-worklet.mjs
1import { Dough } from './dough.mjs';
2
3const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
4
5class DoughProcessor extends AudioWorkletProcessor {
6  constructor() {
7    super();
8    this.dough = new Dough(sampleRate, currentTime);
9    this.port.onmessage = (event) => {
10      if (event.data.spawn) {
11        this.dough.scheduleSpawn(event.data.spawn);
12      } else if (event.data.sample) {
13        this.dough.loadSample(event.data.sample, event.data.channels, event.data.sampleRate);
14      } else if (event.data.samples) {
15        event.data.samples.forEach(([name, channels, sampleRate]) => {
16          this.dough.loadSample(name, channels, sampleRate);
17        });
18      } else {
19        console.log('unrecognized event type', event.data);
20      }
21    };
22  }
23  process(inputs, outputs, params) {
24    if (this.disconnected) {
25      return false;
26    }
27    const output = outputs[0];
28    for (let i = 0; i < output[0].length; i++) {
29      this.dough.update();
30      for (let c = 0; c < output.length; c++) {
31        //prevent speaker blowout via clipping if threshold exceeds
32        output[c][i] = clamp(this.dough.out[c], -1, 1);
33      }
34    }
35    return true; // keep the audio processing going
36  }
37}
38
39registerProcessor('dough-processor', DoughProcessor);