73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 1// Scales as semitone offsets within an octave. "continuous" means no quantization.
3export const SCALES: Record<string, number[] | null> = {
4 continuous: null,
5 chromatic: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
6 major: [0, 2, 4, 5, 7, 9, 11],
7 "natural minor": [0, 2, 3, 5, 7, 8, 10],
8 dorian: [0, 2, 3, 5, 7, 9, 10],
9 lydian: [0, 2, 4, 6, 7, 9, 11],
10 "pentatonic major": [0, 2, 4, 7, 9],
11 "pentatonic minor": [0, 3, 5, 7, 10],
12 "whole tone": [0, 2, 4, 6, 8, 10],
13 "harmonic series": null, // handled specially: partials of the root
14};
16export const SCALE_NAMES = Object.keys(SCALES);
17export const NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
19export function midiToFreq(m: number): number {
20 return 440 * Math.pow(2, (m - 69) / 12);
21}
23/** Snap a (fractional) MIDI pitch to the nearest pitch of the scale. */
24export function quantize(midi: number, scale: string, root: number): number {
25 if (scale === "harmonic series") {
26 // partials of the root an octave or more below the pitch range
27 const f0 = midiToFreq(root + 12 * Math.floor((24 - root) / 12)); // root in octave 1 (≈ 32–62 Hz)
28 const n = Math.max(1, Math.round(midiToFreq(midi) / f0));
29 return 69 + 12 * Math.log2((n * f0) / 440);
30 }
31 const steps = SCALES[scale];
32 if (!steps) return midi;
33 const rel = midi - root;
34 const oct = Math.floor(rel / 12);
35 const within = rel - 12 * oct;
36 let best = steps[0], bestD = Infinity;
37 for (const s of [...steps, 12]) {
38 const d = Math.abs(within - s);
39 if (d < bestD) {
40 bestD = d;
41 best = s;
42 }
43 }
44 return root + 12 * oct + best;
45}