Skip to content

Instantly share code, notes, and snippets.

@ElizabethHudnott
Created October 25, 2024 22:41
Show Gist options
  • Save ElizabethHudnott/1c560b593db248ece846ac3f60b66a55 to your computer and use it in GitHub Desktop.
Save ElizabethHudnott/1c560b593db248ece846ac3f60b66a55 to your computer and use it in GitHub Desktop.
Logic/Arithmetic Operations on Waveforms in wavepot
class Oscillator {
constructor(waveFunction, frequency) {
const tableLength = Math.round(sampleRate / frequency);
const table = new Float32Array(tableLength);
for (let i = 0; i < tableLength; i++) {
table[i] = waveFunction(i / tableLength);
}
this.table = table;
this.period = tableLength / sampleRate;
}
valueAtTime(t) {
const tableLength = this.table.length;
const offset = (t % this.period) * sampleRate;
const offset1 = Math.trunc(offset);
let offset2 = offset1 + 1;
if (offset2 === tableLength) {
offset2 = 0;
}
const value1 = this.table[offset1];
const value2 = this.table[offset2];
const interpolation = offset - offset1;
return value1 * (1 - interpolation) + value2 * interpolation;
}
}
const sine = x => Math.sin(2 * Math.PI * x);
const square = x => x < 0.5 ? 1 : -1;
function and(f1, f2, freq2 = 1) {
return x => Math.min(f1(x), f2((freq2 * x) % 1));
}
function or(f1, f2) {
return x => Math.max(f1(x), f2((freq2 * x) % 1));
}
function xor(f1, f2, freq2 = 1) {
return x => {
const y1 = f1(x);
const y2 = f2((freq2 *x) % 1);
return Math.max(Math.min(y1, 1 - y2), Math.min(1 - y1, y2));
}
}
function hypot(f1, f2, freq2 = 1) {
return x => 2 / Math.SQRT2 * Math.hypot(f1(x), f2((freq2 * x) % 1)) - 1;
}
const wave = new Oscillator(hypot(sine, sine, 2), 220);
function dsp(t) {
return 1 - wave.valueAtTime(t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment