Track octave, range and mono; faster tempos; audio-only WAV recording
- Range: each track's octave (C0 to C6) and number of octaves (1 to 6),
linked together; custom notes follow the octave
- Mono: optionally stop the previous note when a new one starts
- Compact track settings, two per row on wide screens
- Tempo options up to x64 (custom up to x128)
- Record menu: video, or audio only as a 16-bit stereo WAV captured
after the limiter
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 changed files+288−101
README.mdmodified+5−5View file
@@ -18,16 +18,16 @@ Static `index.html`, `style.css` and ES modules, no build step; fonts bundled un
1818 - **Tempo and sound** (top right): the global tempo (40 to 240 bpm, default 120), the big sound on/off button, and the master volume. A track played while the sound is off makes the button pulse.
1919 - **Tracks** (right panel, up to 8): each is an orbit and how it plays. Tracks start paused, so they can be set up first; each has play/pause, restart (from its start) and remove, and *Play all*, *Pause all*, *Restart all* act on every track. The open track shows its controls; click another track's header to open it.
2020 - **Orbit**: click the plot to place (or move) the open track's start, or drag its ring; click any start ring to open its track; shift-click (or *+ Add track*, then click) for a new track. The orbit's dots fill in (larger, brighter), and while it plays a playhead walks it one drive period per beat, with a fading trail of the continuous motion through each period and a ring at each pluck. Changing a parameter or preset restarts nothing: the tracks carry on from where they are under the new equation, their dots recomputed from there, and the old dots (and the old section behind them) fade out as the new ones fill in. Restart takes a track back to its start.
21-- **Track settings**: instrument, rhythm, scale, key, tempo multiple, sustain, volume and velocity. Each but the instrument has a link toggle: linked tracks share one value (change it on any of them and all follow), unlinked ones have their own. By default scale and key are linked.
22-- **Tempo multiple**: each track advances one drive period per tick, at a multiple of the global tempo: ×1 (the default: 2 drive periods a second at 120 bpm), ×2, ×3, ×4, ×6, ×8, ×12, ×16, ×1/2, ×1/3, ×1/4, ×1/6, ×1/8, or a custom number or fraction (1/16 to 32, such as 3/2). Ticks fall on a grid aligned to the beat, so ×2 and ×3 meet on every beat and ×1/2 ticks on every other beat (polyrhythms); a track that starts playing joins at its next tick. Changing the tempo carries the beat on from where it is.
23-- **Notes**: each pluck's pitch is set by x (left to right across the view: C3 to C6), on the track's scale (minor pentatonic by default; major pentatonic, major, minors, whole tone, chromatic, or continuous) in its key (A by default). The key keeps the register and changes which notes x snaps to, so switching key while playing shifts the harmony like a chord change. An island orbit plays a repeating pattern; a chaotic one wanders.
24-- **Custom notes** (the last choice in the Scale menu): pick the notes yourself on a small piano in the track's card, by clicking keys or by pressing them on a MIDI keyboard (Web MIDI: Chrome, Edge or Firefox; the browser asks for permission the first time). Choosing Custom notes starts listening to the keyboard. The keys you hold down together become the notes: press them at once, or one after another without letting go of them all (or with the sustain pedal down); once every key is up, the next press starts a new set. Clicking a key on the piano adds or removes just that note (and, with the sound on, plays it on the track's instrument; keys pressed on the MIDI keyboard aren't played). Keys go to the open track's notes; *Listening…* toggles this, and *Clear* empties them. With *Every octave* (on by default) their pitch classes make a scale across the usual C3 to C6; turn it off and the notes themselves are spread across the view from left to right, lowest to highest, so x picks among exactly those notes. A key change transposes them (the nearer way). The notes go with the scale setting, so linked tracks share them; unlink a track's scale to give it its own. Switching to another scale and back keeps them.
21+- **Track settings**: instrument, rhythm, tempo multiple, scale, key, range, mono, sustain (built-in instruments) or velocity (SoundFonts), and volume, two to a row where the card is wide enough. Each but the instrument has a link toggle: linked tracks share one value (change it on any of them and all follow), unlinked ones have their own. By default scale and key are linked.
22+- **Tempo multiple**: each track advances one drive period per tick, at a multiple of the global tempo: ×1 (the default: 2 drive periods a second at 120 bpm), ×2, ×3, ×4, ×6, ×8, ×12, ×16, ×24, ×32, ×48, ×64, ×1/2, ×1/3, ×1/4, ×1/6, ×1/8, or a custom number or fraction (1/16 to 128, such as 3/2). The fastest blur into a texture or a buzz (×64 at 240 bpm is 256 notes a second), where *Mono* keeps them clean. Ticks fall on a grid aligned to the beat, so ×2 and ×3 meet on every beat and ×1/2 ticks on every other beat (polyrhythms); a track that starts playing joins at its next tick. Changing the tempo carries the beat on from where it is.
23+- **Notes**: each pluck's pitch is set by x (left to right across the view: C3 to C6 by default), on the track's scale (minor pentatonic by default; major pentatonic, major, minors, whole tone, chromatic, or continuous) in its key (A by default). The key keeps the register and changes which notes x snaps to, so switching key while playing shifts the harmony like a chord change. The range sets the register: the note at the left edge (C0 to C6, C3 by default) and the octaves across the view (1 to 6, 3 by default), so a bass line and a melody can share one scale, and fewer octaves make x's notes wider apart. Its two menus are linked together. With *Mono* on, each note stops the track's note before it (a 40 ms fade), so the track plays one note at a time however long the sustain; off (the default), notes ring on and overlap. An island orbit plays a repeating pattern; a chaotic one wanders.
24+- **Custom notes** (the last choice in the Scale menu): pick the notes yourself on a small piano in the track's card, by clicking keys or by pressing them on a MIDI keyboard (Web MIDI: Chrome, Edge or Firefox; the browser asks for permission the first time). Choosing Custom notes starts listening to the keyboard. The keys you hold down together become the notes: press them at once, or one after another without letting go of them all (or with the sustain pedal down); once every key is up, the next press starts a new set. Clicking a key on the piano adds or removes just that note (and, with the sound on, plays it on the track's instrument; keys pressed on the MIDI keyboard aren't played). Keys go to the open track's notes; *Listening…* toggles this, and *Clear* empties them. With *Every octave* (on by default) their pitch classes make a scale across the track's range; turn it off and the notes themselves are spread across the view from left to right, lowest to highest, so x picks among exactly those notes. A key change transposes them (the nearer way), and the range's first menu shifts them by octaves (its second doesn't apply); the piano shows them as they sound, so a key you press sounds as pressed. The notes go with the scale setting, so linked tracks share them; unlink a track's scale to give it its own. Switching to another scale and back keeps them.
2525 - **Rhythm**: *natural, upward* plucks wherever ẋ crosses 0 upward (the left turning point of each swing), at that x and at that moment in the slowed-down motion, so each orbit makes its own rhythm: lilting and nearly regular on an island, uneven in the sea. *Both ways* also plucks at the right turning point. *Steady* (the default) plucks once per drive period, at the section point.
2626 - **Instruments**: harp, marimba, vibraphone, electric piano, music box, ocarina, pizzicato and kalimba (a new track takes the first one not in use). **Sustain** (0.1 to 4 s, default 2) sets how long the notes ring, the same for every voice and pitch, so the voices differ only in timbre and attack, and all start equally loud. **Volume** is the track's level.
2727 - **SoundFonts** (optional): *Load .sf2…* (bottom of the tracks panel) loads one or more files; each one's presets join every track's instrument menu (a group per file), and the open track takes the first file's first preset. The list shows each file, its number of presets and the tracks using it; × removes one (its tracks go back to built-in instruments). Loading a file with the name of one already loaded replaces it, its tracks keeping their presets by name. Samples play as recorded, so Sustain doesn't apply to them; *Velocity* (1 to 127, with a little random jitter per note) picks their velocity layers. Each preset is matched in loudness to the built-in voices at velocity 100 near middle C. The files are remembered in the browser until × removes them.
2828 - **MIDI knobs** (optional): the *Knobs* button by the Equation heading puts a small chip on each equation slider and on the coupling. Click a slider's **+** and turn a knob on your controller (any MIDI control change, such as the knobs of an Arturia MiniLab); from then on that knob moves the slider, smoothly like dragging it. Knobs come in two kinds, told apart as you assign one (a relative knob turned steadily repeats itself, which an absolute one never does): an absolute knob sends its position, 0 to 127, and sweeps the slider's whole range; a relative (endless) one, such as the MiniLab's clickable browse knobs, sends steps left or right (64 ± n, 16 ± n or two's complement), and nudges the slider from where it is, by a 256th of its range a step (at least the slider's own step), more when turned faster. A chip shows its knob (CC number, channel if not 1, ↻ if relative); click it to assign another knob, switch its kind, or unassign it. A knob is assigned to one slider at a time. The assignments are kept in this browser (they belong to the controller, not the session, so they aren't in the session file or undone by Start over), and they work whether the chips are shown or not.
2929 - **Coupling** (optional, off by default; 1 to about 3000 s⁻¹ on a log scale): joins the playing tracks with the same tempo multiple into one system (one system per multiple), each pulled toward their mean by a spring and a damper on its difference (critically damped at rate r), leaving the mean motion as it was. Weakly coupled they nudge each other (and lose the energy of their mismatch, often settling into islands); strongly coupled they fall into step and play in unison, even in the chaotic sea. On the first preset, three sea orbits lock above about 900 s⁻¹. Whenever such a set of tracks changes (one played, paused, moved or removed, or its multiple changed) or the coupling changes, they carry on from where they are; only their dots are recomputed, coupled from there.
30-- **Recording** (*Record* in the header): records a video of the phase space alone (the dots, orbits, trails, plucks and start rings; no axes, labels or track numbers) with the sound as heard (after the master volume), for as long as you like; it turns the sound on. While recording, the header shows the time and size so far; *Stop* ends it, and *Download video* saves it: MP4 (H.264 and AAC) where the browser can record it, else WebM. The video is the plot's size on screen when the recording started (its longer side at most 1920 px; resizing the window meanwhile stretches it), 60 fps at about 8 Mbit/s (some 3.6 GB an hour). Everything you do while recording is in it, parameter changes included. Keep the tab in view: a hidden tab stops drawing frames. The page asks before closing with a recording not yet downloaded.
30+- **Recording** (*Record* in the header, with *Video* or *Audio (.wav)* chosen in the menu beside it, which the browser remembers): *Video* records a video of the phase space alone (the dots, orbits, trails, plucks and start rings; no axes, labels or track numbers) with the sound as heard (after the master volume), for as long as you like; it turns the sound on. While recording, the header shows the time and size so far; *Stop* ends it, and *Download video* saves it: MP4 (H.264 and AAC) where the browser can record it, else WebM. The video is the plot's size on screen when the recording started (its longer side at most 1920 px; resizing the window meanwhile stretches it), 60 fps at about 8 Mbit/s (some 3.6 GB an hour). Everything you do while recording is in it, parameter changes included. Keep the tab in view: a hidden tab stops drawing frames. The page asks before closing with a recording not yet downloaded. *Audio (.wav)* records just the sound as heard (after the master volume and limiter), sample for sample, into a 16-bit stereo WAV at the audio device's rate (usually 48 kHz, about 11.5 MB a minute), saved with *Download WAV*. Keep the tab in view for this too: the notes are scheduled as the page draws, so a hidden tab falls silent.
3131 - **Session** (bottom of the equation panel): everything (the equation, coupling, tempo, master volume, and every track's settings, start, play state and where its playhead is) is saved in the browser as you go and restored on reload; the sound starts off. *Save to file* downloads it all as JSON, every loaded SoundFont included (their bytes in base64), and *Open file…* restores such a file, adding its SoundFonts (replacing loaded ones of the same name). Each track remembers its SoundFont by file name and its preset by number and name, so it finds them again even if the files are loaded in another order or a file changed. *Start over* goes back to the defaults (the SoundFonts stay).
3232 - **Parameters**: f₀ (negative: a double well), α, δ, F, Ω/2π, and the view's half-width in x. Presets: double well (islands in a sea; gentle drive with a thin chaotic layer; strong drive), pure cubic, hardening resonance island, and a damped strange attractor.
3333
app/index.htmlmodified+4−0View file
@@ -21,6 +21,10 @@
2121 <output></output>
2222 </label>
2323 <div class="rec">
24+ <select id="rec-kind" class="rec-kind" aria-label="What to record" title="What to record: a video with the sound, or the sound alone as a WAV file">
25+ <option value="video">Video</option>
26+ <option value="audio">Audio (.wav)</option>
27+ </select>
2428 <button id="record" class="rec-btn" aria-pressed="false"><span class="rec-dot" aria-hidden="true"></span><span class="rec-label">Record</span></button>
2529 <span id="rec-status" class="rec-status" aria-live="polite" hidden></span>
2630 <button id="rec-download" class="small" hidden></button>
app/js/soundfont.jsmodified+4−10View file
@@ -197,7 +197,8 @@ export function makeInstrument(sf, presetIndex) {
197197 return { x, rate: r.rate };
198198 },
199199 // start a note of MIDI key (may be fractional) at velocity vel, at time t,
200- // into node `out`; returns { stop(t), end } for the voice's note limit
200+ // into node `out`; returns { stop(t), end }: stop ends its samples at t
201+ // (the caller fades it out first)
201202 play(ctx, key, vel, t, out) {
202203 const nodes = [];
203204 let end = t;
@@ -230,19 +231,12 @@ export function makeInstrument(sf, presetIndex) {
230231 node.connect(out);
231232 src.start(t);
232233 src.stop(stopAt);
233- nodes.push({ src, env });
234+ nodes.push({ src, stopAt });
234235 end = Math.max(end, stopAt);
235236 }
236237 return {
237238 end,
238- stop(at) {
239- for (const { src, env } of nodes) {
240- env.gain.cancelScheduledValues(at);
241- env.gain.setValueAtTime(env.gain.value, at);
242- env.gain.linearRampToValueAtTime(0, at + 0.04);
243- src.stop(at + 0.05);
244- }
245- },
239+ stop(at) { for (const n of nodes) if (at < n.stopAt) n.src.stop(at); },
246240 };
247241 },
248242 };
app/js/voices.jsmodified+93−17View file
@@ -43,18 +43,18 @@ export const SCALES = [
4343 ];
4444
4545 const LOW = 130.81; // C3, the pitch at the left edge of the view
46-const OCTAVES = 3; // up to C6 at the right edge
46+export const OCTAVES = 3; // by default, up to C6 at the right edge
4747
4848 // The pitch (Hz) for u in [0, 1] (the left to right edge of the view): the
4949 // notes of the scale in the given key (0 = C, ..., 11 = B) that lie within
50-// OCTAVES octaves from LOW, spread evenly across the view; or continuous.
50+// `octaves` octaves from LOW, spread evenly across the view; or continuous.
5151 // The register stays put when the key changes, so a key change shifts the
5252 // harmony, like a chord change.
53-export function pitchOf(u, scale, key = 0) {
53+export function pitchOf(u, scale, key = 0, octaves = OCTAVES) {
5454 u = Math.min(1, Math.max(0, u));
55- if (!scale.steps) return LOW * 2 ** (OCTAVES * u);
55+ if (!scale.steps) return LOW * 2 ** (octaves * u);
5656 const notes = [];
57- for (let s = 0; s <= 12 * OCTAVES; s++) {
57+ for (let s = 0; s <= 12 * octaves; s++) {
5858 if (scale.steps.includes((((s - key) % 12) + 12) % 12)) notes.push(s);
5959 }
6060 return LOW * 2 ** (notes[Math.round(u * (notes.length - 1))] / 12);
@@ -237,6 +237,39 @@ function reverbImpulse(ctx, seconds = 1.6) {
237237 return buf;
238238 }
239239
240+// The audio worklet that records the output: stereo frames, posted in blocks
241+// of 8192 (and what is left when told to stop).
242+const CAPTURE_WORKLET = `
243+class CaptureTap extends AudioWorkletProcessor {
244+ constructor() {
245+ super();
246+ this.n = 0;
247+ this.l = new Float32Array(8192);
248+ this.r = new Float32Array(8192);
249+ this.done = false;
250+ this.port.onmessage = () => { this.post(true); this.done = true; };
251+ }
252+ post(last) {
253+ this.port.postMessage({ l: this.l.slice(0, this.n), r: this.r.slice(0, this.n), last });
254+ this.n = 0;
255+ }
256+ process(inputs) {
257+ if (this.done) return false;
258+ const ch = inputs[0];
259+ if (ch.length) {
260+ const a = ch[0], b = ch[1] || ch[0];
261+ for (let i = 0; i < a.length; i++) {
262+ this.l[this.n] = a[i];
263+ this.r[this.n] = b[i];
264+ if (++this.n === this.l.length) this.post(false);
265+ }
266+ }
267+ return true;
268+ }
269+}
270+registerProcessor('capture-tap', CaptureTap);
271+`;
272+
240273 export function createSynth() {
241274 const ctx = new AudioContext();
242275 const master = ctx.createGain();
@@ -299,6 +332,39 @@ export function createSynth() {
299332 }
300333 return this.tap.stream;
301334 },
335+ // Record the output as heard, sample for sample: onData(left, right)
336+ // gets Float32Arrays of frames as they come (at ctx.sampleRate).
337+ // Resolves to stop(), which resolves once the last frames are in.
338+ async capture(onData) {
339+ if (!this.tapModule) {
340+ const url = URL.createObjectURL(new Blob([CAPTURE_WORKLET], { type: 'text/javascript' }));
341+ this.tapModule = ctx.audioWorklet.addModule(url).finally(() => URL.revokeObjectURL(url));
342+ }
343+ await this.tapModule;
344+ const node = new AudioWorkletNode(ctx, 'capture-tap', {
345+ numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1],
346+ channelCount: 2, channelCountMode: 'explicit', channelInterpretation: 'speakers',
347+ });
348+ // (an output to the destination, silent, so the node is pulled)
349+ const mute = ctx.createGain();
350+ mute.gain.value = 0;
351+ limiter.connect(node);
352+ node.connect(mute).connect(ctx.destination);
353+ let finish;
354+ const finished = new Promise((r) => { finish = r; });
355+ node.port.onmessage = (e) => {
356+ if (e.data.l.length) onData(e.data.l, e.data.r);
357+ if (e.data.last) finish();
358+ };
359+ return async () => {
360+ node.port.postMessage('stop');
361+ // (a suspended context sends nothing more)
362+ await Promise.race([finished, new Promise((r) => setTimeout(r, 1000))]);
363+ limiter.disconnect(node);
364+ node.disconnect();
365+ mute.disconnect();
366+ };
367+ },
302368 // a track's volume (its notes, sounding and to come)
303369 setTrackVolume(id, v) { track(id).gain.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
304370 // a track removed: its notes fade out
@@ -312,18 +378,19 @@ export function createSynth() {
312378 // a note on track `id` of `voice` (an index into VOICES, or a SoundFont
313379 // instrument from makeInstrument, played at MIDI velocity vel) at freq,
314380 // at time `when` (the context's clock), panned by pan in [-1, 1], at
315- // level gain; the built-in voices ring for `sustain` s
316- play(id, voice, freq, when, { pan = 0, gain = 1, sustain = SUSTAIN.default, vel = 100 } = {}) {
381+ // level gain; the built-in voices ring for `sustain` s; mono: the track's
382+ // notes still sounding fade out as it starts
383+ play(id, voice, freq, when, { pan = 0, gain = 1, sustain = SUSTAIN.default, vel = 100, mono = false } = {}) {
317384 const tr = track(id);
318385 const level = ctx.createGain();
319386 const panner = ctx.createStereoPanner();
320387 panner.pan.value = pan;
321388 level.connect(panner).connect(tr.gain);
322389 const t = Math.max(when, ctx.currentTime);
323- let note;
390+ let sound; // { end, stop(at): end it at `at` }
324391 if (typeof voice !== 'number') {
325392 level.gain.value = gain * sfGain(voice);
326- note = voice.play(ctx, 69 + 12 * Math.log2(freq / 440), vel, t, level);
393+ sound = voice.play(ctx, 69 + 12 * Math.log2(freq / 440), vel, t, level);
327394 } else {
328395 const key = `${voice}:${sustain.toFixed(2)}:${Math.round(freq * 10)}`;
329396 let buf = cache.get(key);
@@ -337,16 +404,25 @@ export function createSynth() {
337404 level.gain.value = gain;
338405 src.connect(level);
339406 src.start(t);
340- note = {
341- end: t + buf.duration,
342- stop(at) {
343- level.gain.setValueAtTime(level.gain.value, at);
344- level.gain.linearRampToValueAtTime(0, at + 0.04);
345- src.stop(at + 0.05);
346- },
347- };
407+ sound = { end: t + buf.duration, stop: (at) => src.stop(at) };
348408 }
409+ // a note stopped at `at` (perhaps still to come) fades out over 40 ms
410+ // (its level is steady, so the ramp starts from where it is)
411+ const note = {
412+ start: t,
413+ end: sound.end,
414+ stop(at) {
415+ if (at >= this.end) return;
416+ level.gain.setValueAtTime(level.gain.value, Math.max(at, ctx.currentTime));
417+ level.gain.linearRampToValueAtTime(0, Math.max(at, ctx.currentTime) + 0.04);
418+ sound.stop(Math.max(at, ctx.currentTime) + 0.05);
419+ this.end = Math.min(this.end, at + 0.05);
420+ },
421+ };
349422 const list = tr.sounding;
423+ if (mono) {
424+ for (const n of list) if (n.start < t) n.stop(t);
425+ }
350426 list.push(note);
351427 // drop those that have finished by now, then fade the excess
352428 while (list.length && list[0].end < ctx.currentTime) list.shift();
app/main.jsmodified+171−64View file
@@ -34,7 +34,7 @@
3434 // move).
3535
3636 import { createStepper, physicsOf, X_MAX } from './js/duffing.js';
37-import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js';
37+import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, OCTAVES, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js';
3838 import { midiSupported, openMidi } from './js/midi.js';
3939 import { forgetSoundFont, loadSaved, makeInstrument, parseSF2, saveSoundFont } from './js/soundfont.js';
4040 import { PRESETS } from './js/presets.js';
@@ -77,12 +77,20 @@ const SCALE_SHORT = {
7777 Chromatic: 'chromatic', Continuous: 'continuous',
7878 };
7979 // the settings that can be linked (shared by the linked tracks), and their defaults
80-const SETTINGS = ['rhythm', 'scale', 'key', 'rate', 'sustain', 'volume', 'velocity'];
80+const SETTINGS = ['rhythm', 'scale', 'key', 'octave', 'rate', 'sustain', 'mono', 'volume', 'velocity'];
8181 const DEFAULTS = {
82- rhythm: 'steady', scale: SCALES.findIndex((s) => s.name === DEFAULT_SCALE), key: DEFAULT_KEY,
83- rate: '1', sustain: SUSTAIN.default, volume: 1, velocity: 100,
82+ rhythm: 'steady', scale: SCALES.findIndex((s) => s.name === DEFAULT_SCALE), key: DEFAULT_KEY, octave: 0,
83+ rate: '1', sustain: SUSTAIN.default, mono: false, volume: 1, velocity: 100,
8484 };
8585 const LINKED_BY_DEFAULT = ['scale', 'key'];
86+// a track's range: its octave, the shift (octaves) of everything it plays
87+// (so the view's left edge is C3 shifted), and 'span', the number of octaves
88+// across the view, linked along with the octave
89+const OCTAVE_SHIFTS = [-3, -2, -1, 0, 1, 2, 3];
90+const SPANS = [1, 2, 3, 4, 5, 6];
91+DEFAULTS.span = OCTAVES;
92+const octaveLabel = (o) => (o > 0 ? `+${o}` : o < 0 ? `−${-o}` : '0');
93+const cName = (o) => `C${3 + o}`; // the note at the left edge, octave o
8694 // The 'Custom notes' scale (the scale setting's value CUSTOM): its notes are
8795 // in the setting 'notes', which is linked along with the scale: MIDI note
8896 // numbers (sorted), as entered in key `ref`, so a change of key transposes
@@ -90,14 +98,15 @@ const LINKED_BY_DEFAULT = ['scale', 'key'];
9098 // across the usual three octaves), rather than just those notes.
9199 const CUSTOM = 'custom';
92100 DEFAULTS.notes = { notes: [], ref: DEFAULT_KEY, every: true };
93-const VALUES = [...SETTINGS, 'notes']; // a track's values (the settings, and the custom notes)
94-const linkOf = (p) => (p === 'notes' ? 'scale' : p);
101+const VALUES = [...SETTINGS, 'notes', 'span']; // a track's values (the settings, the custom notes, and the span)
102+const COMPANIONS = { notes: 'scale', span: 'octave' };
103+const linkOf = (p) => COMPANIONS[p] ?? p;
95104 // the global tempo (bpm)
96105 const TEMPO = { min: 40, max: 240, default: 120 };
97106 // a track's tempo multiple: ticks (drive periods) per beat, as text ('3',
98107 // '1/2', '1.5'); the menu's choices, and the range of custom ones
99-const RATES = ['16', '12', '8', '6', '4', '3', '2', '1', '1/2', '1/3', '1/4', '1/6', '1/8'];
100-const RATE_RANGE = { min: 1 / 16, max: 32 };
108+const RATES = ['64', '48', '32', '24', '16', '12', '8', '6', '4', '3', '2', '1', '1/2', '1/3', '1/4', '1/6', '1/8'];
109+const RATE_RANGE = { min: 1 / 16, max: 128 };
101110 const RANGES = {
102111 sustain: { label: 'Sustain', min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, fmt: (v) => `${v.toFixed(1)} s`, title: 'How long each note rings (built-in instruments)' },
103112 volume: { label: 'Volume', min: 0, max: 1, step: 0.01, fmt: (v) => `${Math.round(100 * v)}%` },
@@ -136,7 +145,7 @@ let dirty = false; // the equation changed: reset at the next frame
136145 let theme;
137146 let soundfonts = []; // the loaded .sf2 files: { id, fileName, bytes, sf (parsed), insts: Map(preset -> instrument) }
138147 let nextFontId = 1;
139-let recording = null; // { recorder, chunks, mime, started } while recording
148+let recording = null; // while recording: { kind: 'video', recorder, chunks, mime, started } or { kind: 'audio', stop, chunks, frames, rate, started }
140149 let recorded = null; // { blob, mime, seconds, saved } once stopped
141150 let restored = false; // the saved state has been restored (until then, nothing is saved)
142151
@@ -366,19 +375,25 @@ const noteName = (m) => `${KEYS[m % 12]}${Math.floor(m / 12) - 1}`;
366375 const pc = (n) => ((n % 12) + 12) % 12;
367376 // the shift (semitones) of custom notes c in key `key`: the nearer way from c.ref
368377 const shiftOf = (c, key) => { const d = pc(key - c.ref); return d > 6 ? d - 12 : d; };
369-// a track's custom notes as they sound (in its key)
370-const soundingNotes = (t) => { const c = val(t, 'notes'); const d = shiftOf(c, val(t, 'key')); return c.notes.map((n) => n + d); };
378+// the shift (semitones) from a track's custom notes as stored to as they
379+// sound: its key's, and its octave's
380+const offsetOf = (t) => shiftOf(val(t, 'notes'), val(t, 'key')) + 12 * val(t, 'octave');
381+// a track's custom notes as they sound (in its key and octave)
382+const soundingNotes = (t) => { const d = offsetOf(t); return val(t, 'notes').notes.map((n) => n + d); };
371383 const isCustom = (t) => val(t, 'scale') === CUSTOM;
384+// custom notes played as they are (not as a scale), so the span is moot
385+const exact = (t) => isCustom(t) && !val(t, 'notes').every;
372386
373387 // the pitch (Hz) a track plays at u in [0, 1] (the left to right edge of the
374388 // view), or null (custom notes, but none yet): custom notes spread evenly
375389 // over the view (or as a scale), or the scale's notes
376390 function pitchFor(t, u) {
377391 const key = val(t, 'key');
378- if (!isCustom(t)) return pitchOf(u, SCALES[val(t, 'scale')], key);
392+ const up = 2 ** val(t, 'octave');
393+ if (!isCustom(t)) return up * pitchOf(u, SCALES[val(t, 'scale')], key, val(t, 'span'));
379394 const c = val(t, 'notes');
380395 if (!c.notes.length) return null;
381- if (c.every) return pitchOf(u, { steps: [...new Set(c.notes.map((n) => pc(n - c.ref)))] }, key);
396+ if (c.every) return up * pitchOf(u, { steps: [...new Set(c.notes.map((n) => pc(n - c.ref)))] }, key, val(t, 'span'));
382397 const ns = soundingNotes(t);
383398 return midiHz(ns[Math.round(Math.min(1, Math.max(0, u)) * (ns.length - 1))]);
384399 }
@@ -415,7 +430,7 @@ function beat(ts, time, dt, together, gain) {
415430 const freq = pitchFor(t, u);
416431 if (freq == null) continue;
417432 synth.play(t.id, voice, freq, n.t, {
418- pan: Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain, sustain: val(t, 'sustain'), vel: velocity(t),
433+ pan: Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain, sustain: val(t, 'sustain'), vel: velocity(t), mono: val(t, 'mono'),
419434 });
420435 }
421436 }
@@ -859,10 +874,20 @@ function scaleText(t) {
859874 return `${KEYS[val(t, 'key')]} ${SCALE_SHORT[s.name] ?? s.name}`;
860875 }
861876
877+// a track's range, for its summary, if not the usual: C2–C4, or (exact
878+// custom notes) +1 oct
879+function rangeText(t) {
880+ const o = val(t, 'octave');
881+ const span = val(t, 'span');
882+ if (exact(t)) return o ? ` ${octaveLabel(o)} oct` : '';
883+ return o || span !== OCTAVES ? ` ${cName(o)}–${cName(o + span)}` : '';
884+}
885+
862886 function summary(t) {
863887 if (!t.start) return 'No start yet: click the plot';
864888 const r = RHYTHMS.find((q) => q.value === val(t, 'rhythm'));
865- const parts = [scaleText(t), rateLabel(t), r.short];
889+ const parts = [`${scaleText(t)}${rangeText(t)}`, rateLabel(t), r.short];
890+ if (val(t, 'mono')) parts.push('mono');
866891 if (t.escaped) parts.push('escaped');
867892 return parts.join(' · ');
868893 }
@@ -918,10 +943,12 @@ function notesEditor(t) {
918943 const sounding = soundingNotes(t);
919944 const on = new Set(sounding);
920945 const pcs = c.every ? new Set(sounding.map(pc)) : null;
921- // C3 to B5 (or to C6, the top of the scale's range, in every octave),
946+ // the range (every octave: the scale's, C3 to C6 shifted by the octave, or
947+ // wider or narrower; else C3 to B5 shifted),
922948 // widened by octaves to take in every note
923- let lo = 48;
924- let hi = c.every ? 84 : 83;
949+ const o = 12 * val(t, 'octave');
950+ let lo = 48 + o;
951+ let hi = (c.every ? 12 * val(t, 'span') : 35) + 48 + o;
925952 if (sounding.length) {
926953 lo = Math.min(lo, 12 * Math.floor(sounding[0] / 12));
927954 hi = Math.max(hi, 12 * Math.ceil((sounding[sounding.length - 1] + 1) / 12) - 1);
@@ -969,7 +996,7 @@ function refreshNotesEditor() {
969996 function toggleNote(t, m) {
970997 let c = val(t, 'notes');
971998 if (!c.notes.length) c = { ...c, ref: val(t, 'key') };
972- const n = m - shiftOf(c, val(t, 'key'));
999+ const n = m - shiftOf(c, val(t, 'key')) - 12 * val(t, 'octave');
9731000 const has = c.every ? c.notes.some((q) => pc(q) === pc(n)) : c.notes.includes(n);
9741001 const notes = has
9751002 ? c.notes.filter((q) => (c.every ? pc(q) !== pc(n) : q !== n))
@@ -1237,7 +1264,7 @@ function midiNote(m, on) {
12371264 function addNote(t, m, fresh) {
12381265 let c = val(t, 'notes');
12391266 if (fresh || !c.notes.length) c = { ...c, notes: [], ref: val(t, 'key') };
1240- const n = m - shiftOf(c, val(t, 'key'));
1267+ const n = m - shiftOf(c, val(t, 'key')) - 12 * val(t, 'octave');
12411268 if (!c.notes.includes(n)) setValue(t, 'notes', { ...c, notes: [...c.notes, n].sort((a, b) => a - b) });
12421269 else setValue(t, 'notes', c);
12431270 tracks.forEach(updateTrack);
@@ -1246,6 +1273,8 @@ function addNote(t, m, fresh) {
12461273 function trackBody(t) {
12471274 const sf = isSoundFont(t);
12481275 const lk = (p) => (t.linked[p] ? ' linked' : '');
1276+ const opt = (value, text, on) => `<option value="${value}"${on ? ' selected' : ''}>${text}</option>`;
1277+ const ex = exact(t);
12491278 return `<div class="track-body">
12501279 <div class="trow start-row">
12511280 <span></span><span class="lbl">Start</span>
@@ -1255,23 +1284,35 @@ function trackBody(t) {
12551284 <span></span><span class="lbl">Instrument</span>
12561285 <select data-instrument aria-label="Instrument">${instrumentOptions(t)}</select>
12571286 </div>
1258- <div class="trow${lk('rhythm')}">
1259- ${linkButton(t, 'rhythm')}<span class="lbl">Rhythm</span>
1260- <select data-p="rhythm" aria-label="Rhythm">${RHYTHMS.map((r) => `<option value="${r.value}"${r.value === val(t, 'rhythm') ? ' selected' : ''}>${r.name}</option>`).join('')}</select>
1261- </div>
1262- <div class="trow${lk('scale')}">
1263- ${linkButton(t, 'scale')}<span class="lbl">Scale</span>
1264- <select data-p="scale" aria-label="Scale">${SCALES.map((s, i) => `<option value="${i}"${i === val(t, 'scale') ? ' selected' : ''}>${s.name}</option>`).join('')}<option value="${CUSTOM}"${isCustom(t) ? ' selected' : ''}>Custom notes…</option></select>
1265- </div>
1266- ${isCustom(t) ? notesEditor(t) : ''}
1267- <div class="trow${lk('key')}">
1268- ${linkButton(t, 'key')}<span class="lbl">Key</span>
1269- <div class="keys" role="group" aria-label="Key">${KEYS.map((k, i) => `<button data-key="${i}" aria-pressed="${i === val(t, 'key')}">${k}</button>`).join('')}</div>
1287+ <div class="tgrid">
1288+ <div class="trow${lk('rhythm')}">
1289+ ${linkButton(t, 'rhythm')}<span class="lbl">Rhythm</span>
1290+ <select data-p="rhythm" aria-label="Rhythm">${RHYTHMS.map((r) => opt(r.value, r.name, r.value === val(t, 'rhythm'))).join('')}</select>
1291+ </div>
1292+ ${rateRow(t)}
1293+ <div class="trow${lk('scale')}">
1294+ ${linkButton(t, 'scale')}<span class="lbl">Scale</span>
1295+ <select data-p="scale" aria-label="Scale">${SCALES.map((s, i) => opt(i, s.name, i === val(t, 'scale'))).join('')}${opt(CUSTOM, 'Custom notes…', isCustom(t))}</select>
1296+ </div>
1297+ <div class="trow${lk('key')}">
1298+ ${linkButton(t, 'key')}<span class="lbl">Key</span>
1299+ <select data-p="key" aria-label="Key">${KEYS.map((k, i) => opt(i, k, i === val(t, 'key'))).join('')}</select>
1300+ </div>
1301+ ${isCustom(t) ? notesEditor(t) : ''}
1302+ <div class="trow${lk('octave')}" title="${ex ? 'Shift the notes by whole octaves' : 'The note at the left edge of the plot, and the octaves across it'}">
1303+ ${linkButton(t, 'octave')}<span class="lbl">Range</span>
1304+ <div class="pair">
1305+ <select data-p="octave" aria-label="${ex ? 'Octave shift' : 'Lowest note'}">${OCTAVE_SHIFTS.map((o) => opt(o, ex ? (o ? `${octaveLabel(o)} oct` : 'as played') : `from ${cName(o)}`, o === val(t, 'octave'))).join('')}</select>
1306+ <select data-p="span" aria-label="Octaves across the plot"${ex ? ' disabled title="Exact custom notes: the notes set the range"' : ''}>${SPANS.map((n) => opt(n, `${n} oct`, n === val(t, 'span'))).join('')}</select>
1307+ </div>
1308+ </div>
1309+ <div class="trow${lk('mono')}" title="Stop the note still ringing when the next one starts">
1310+ ${linkButton(t, 'mono')}<span class="lbl">Mono</span>
1311+ <label class="mono-check"><input type="checkbox" data-p="mono"${val(t, 'mono') ? ' checked' : ''}> one note at a time</label>
1312+ </div>
1313+ ${sf ? rangeRow(t, 'velocity') : rangeRow(t, 'sustain')}
1314+ ${rangeRow(t, 'volume')}
12701315 </div>
1271- ${rateRow(t)}
1272- ${rangeRow(t, 'sustain', sf)}
1273- ${rangeRow(t, 'volume')}
1274- ${rangeRow(t, 'velocity', !sf)}
12751316 <p class="link-note">${ICONS.link} linked settings are shared by every track that links them</p>
12761317 </div>`;
12771318 }
@@ -1374,14 +1415,6 @@ function buildTrackControls() {
13741415 refreshNotesEditor();
13751416 return;
13761417 }
1377- const keyBtn = e.target.closest('button[data-key]');
1378- if (keyBtn) {
1379- setValue(t, 'key', Number(keyBtn.dataset.key));
1380- for (const b of keyBtn.parentElement.children) b.setAttribute('aria-pressed', b === keyBtn);
1381- tracks.forEach(updateTrack);
1382- refreshNotesEditor();
1383- return;
1384- }
13851418 if (!act) return;
13861419 switch (act.dataset.act) {
13871420 case 'play': setPlaying(t, !t.playing); break;
@@ -1452,10 +1485,16 @@ function buildTrackControls() {
14521485 renderTracks();
14531486 // (the keyboard's keys go to the notes from the start)
14541487 if (custom && midiSupported() && !midi.listening) setListening(true);
1455- } else if (e.target.matches('input[data-every]')) {
1456- setValue(t, 'notes', { ...val(t, 'notes'), every: e.target.checked });
1488+ } else if (e.target.matches('select[data-p="key"], select[data-p="octave"], select[data-p="span"]')) {
1489+ setValue(t, e.target.dataset.p, Number(e.target.value));
14571490 tracks.forEach(updateTrack);
14581491 refreshNotesEditor();
1492+ } else if (e.target.matches('input[data-p="mono"]')) {
1493+ setValue(t, 'mono', e.target.checked);
1494+ tracks.forEach(updateTrack);
1495+ } else if (e.target.matches('input[data-every]')) {
1496+ setValue(t, 'notes', { ...val(t, 'notes'), every: e.target.checked });
1497+ renderTracks(); // (the range's menus change with it)
14591498 }
14601499 });
14611500 $('add-track').addEventListener('click', addTrack);
@@ -1720,12 +1759,15 @@ function readSettings(o, base) {
17201759 const c = o.notes;
17211760 if (c && typeof c === 'object' && Array.isArray(c.notes)) {
17221761 r.notes = {
1723- notes: [...new Set(c.notes.filter((n) => Number.isInteger(n) && n >= 0 && n <= 127))].sort((a, b) => a - b),
1762+ notes: [...new Set(c.notes.filter((n) => Number.isInteger(n) && n >= -36 && n <= 163))].sort((a, b) => a - b),
17241763 ref: Number.isInteger(c.ref) && c.ref >= 0 && c.ref < 12 ? c.ref : DEFAULT_KEY,
17251764 every: !!c.every,
17261765 };
17271766 }
17281767 if (Number.isInteger(o.key) && o.key >= 0 && o.key < KEYS.length) r.key = o.key;
1768+ if (OCTAVE_SHIFTS.includes(o.octave)) r.octave = o.octave;
1769+ if (SPANS.includes(o.span)) r.span = o.span;
1770+ if (typeof o.mono === 'boolean') r.mono = o.mono;
17291771 if (o.rate != null && !Number.isNaN(parseRate(o.rate))) r.rate = String(o.rate);
17301772 for (const p of ['sustain', 'volume', 'velocity']) if (finite(o[p])) r[p] = clamp(o[p], RANGES[p].min, RANGES[p].max);
17311773 return r;
@@ -1873,10 +1915,11 @@ function buildSessionControls() {
18731915 document.addEventListener('visibilitychange', () => { if (document.hidden) autosave(); });
18741916 }
18751917
1876-// ---- recording a video ------------------------------------------------------------
1877-// The video is the phase space alone (no axes or labels), drawn each frame
1878-// onto a canvas of its own at the plot's size when the recording started
1879-// (its longer side at most REC_MAX px); the audio is the sound as heard.
1918+// ---- recording -------------------------------------------------------------------
1919+// A video: the phase space alone (no axes or labels), drawn each frame onto a
1920+// canvas of its own at the plot's size when the recording started (its longer
1921+// side at most REC_MAX px), with the sound as heard. Or just the sound, as
1922+// heard, sample for sample, into a 16-bit stereo WAV file.
18801923
18811924 const REC_MAX = 1920;
18821925 const REC_FPS = 60;
@@ -1889,7 +1932,10 @@ const REC_TYPES = [
18891932 'video/webm;codecs=vp8,opus',
18901933 'video/webm',
18911934 ];
1892-const canRecord = () => typeof MediaRecorder !== 'undefined' && !!recCanvas.captureStream;
1935+const canRecordVideo = () => typeof MediaRecorder !== 'undefined' && !!recCanvas.captureStream;
1936+const canRecordAudio = () => typeof AudioWorkletNode !== 'undefined';
1937+const REC_KIND_KEY = 'duffing-islands:rec-kind';
1938+const recKind = () => $('rec-kind').value;
18931939
18941940 // a frame of the video: the plot rect r of the screen, scaled to the canvas
18951941 function drawRecordingFrame(r) {
@@ -1909,7 +1955,8 @@ const fmtTime = (sec) => {
19091955 const fmtSize = (bytes) => (bytes < 1e9 ? `${(bytes / 1e6).toFixed(bytes < 1e7 ? 1 : 0)} MB` : `${(bytes / 1e9).toFixed(2)} GB`);
19101956
19111957 function startRecording() {
1912- if (!canRecord()) return;
1958+ if (recKind() === 'audio') { startAudioRecording(); return; }
1959+ if (!canRecordVideo()) return;
19131960 // the audio is the sound as heard, so the sound goes on
19141961 if (!soundOn) setSound(true);
19151962 discardRecording();
@@ -1942,12 +1989,65 @@ function startRecording() {
19421989 recorder.onerror = (e) => recMessage(`Recording failed: ${e.error?.message ?? 'unknown error'}`);
19431990 // (in slices, so a long recording is collected as it goes)
19441991 recorder.start(1000);
1945- recording = { recorder, chunks, mime, started: performance.now() };
1992+ recording = { kind: 'video', recorder, chunks, mime, started: performance.now() };
19461993 renderRecording();
19471994 }
19481995
1996+// the sound alone: its frames, as they come, kept as 16-bit stereo
1997+async function startAudioRecording() {
1998+ if (!canRecordAudio()) return;
1999+ if (!soundOn) setSound(true);
2000+ discardRecording();
2001+ const rec = { kind: 'audio', stop: null, chunks: [], frames: 0, rate: synth.ctx.sampleRate, started: performance.now() };
2002+ recording = rec;
2003+ renderRecording();
2004+ try {
2005+ rec.stop = await synth.capture((l, r) => {
2006+ const out = new Int16Array(2 * l.length);
2007+ for (let i = 0; i < l.length; i++) {
2008+ out[2 * i] = Math.round(32767 * Math.max(-1, Math.min(1, l[i])));
2009+ out[2 * i + 1] = Math.round(32767 * Math.max(-1, Math.min(1, r[i])));
2010+ }
2011+ rec.chunks.push(out);
2012+ rec.frames += l.length;
2013+ });
2014+ } catch (err) {
2015+ recording = null;
2016+ renderRecording();
2017+ recMessage(`Can't record here: ${err.message}`);
2018+ return;
2019+ }
2020+ // (stopped while starting)
2021+ if (rec.stopping) finishAudioRecording(rec);
2022+}
2023+
2024+async function finishAudioRecording(rec) {
2025+ await rec.stop();
2026+ recording = null;
2027+ recorded = { blob: wavBlob(rec.chunks, rec.frames, rec.rate), mime: 'audio/wav', seconds: rec.frames / rec.rate, saved: false };
2028+ renderRecording();
2029+}
2030+
2031+// a 16-bit stereo WAV file of interleaved samples
2032+function wavBlob(chunks, frames, rate) {
2033+ const h = new DataView(new ArrayBuffer(44));
2034+ const str = (o, t) => { for (let i = 0; i < t.length; i++) h.setUint8(o + i, t.charCodeAt(i)); };
2035+ const bytes = 4 * frames;
2036+ str(0, 'RIFF'); h.setUint32(4, 36 + bytes, true); str(8, 'WAVE');
2037+ str(12, 'fmt '); h.setUint32(16, 16, true); h.setUint16(20, 1, true); h.setUint16(22, 2, true);
2038+ h.setUint32(24, rate, true); h.setUint32(28, 4 * rate, true); h.setUint16(32, 4, true); h.setUint16(34, 16, true);
2039+ str(36, 'data'); h.setUint32(40, bytes, true);
2040+ return new Blob([h, ...chunks], { type: 'audio/wav' });
2041+}
2042+
19492043 function stopRecording() {
1950- if (recording?.recorder.state !== 'inactive') recording?.recorder.stop();
2044+ const rec = recording;
2045+ if (!rec) return;
2046+ if (rec.kind === 'audio') {
2047+ if (rec.stopping) return;
2048+ rec.stopping = true;
2049+ if (rec.stop) finishAudioRecording(rec);
2050+ } else if (rec.recorder.state !== 'inactive') rec.recorder.stop();
19512051 }
19522052
19532053 function discardRecording() {
@@ -1959,7 +2059,7 @@ function saveRecording() {
19592059 if (!recorded) return;
19602060 const d = new Date();
19612061 const pad = (n) => String(n).padStart(2, '0');
1962- const ext = recorded.mime.includes('mp4') ? 'mp4' : 'webm';
2062+ const ext = recorded.mime === 'audio/wav' ? 'wav' : recorded.mime.includes('mp4') ? 'mp4' : 'webm';
19632063 downloadBlob(recorded.blob, `duffing-islands-${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.${ext}`);
19642064 recorded.saved = true;
19652065 }
@@ -1971,11 +2071,16 @@ function renderRecording() {
19712071 const on = !!recording;
19722072 btn.setAttribute('aria-pressed', on);
19732073 btn.querySelector('.rec-label').textContent = on ? 'Stop' : 'Record';
1974- btn.title = on ? 'Stop recording' : 'Record a video of the phase space with the sound (the sound goes on)';
2074+ const audio = recKind() === 'audio';
2075+ btn.title = on ? 'Stop recording'
2076+ : audio ? 'Record the sound as a WAV file (the sound goes on)' : 'Record a video of the phase space with the sound (the sound goes on)';
2077+ btn.disabled = !(audio ? canRecordAudio() : canRecordVideo());
2078+ if (btn.disabled) btn.title = `Recording ${audio ? 'audio' : 'video'} isn't supported in this browser`;
2079+ $('rec-kind').disabled = on;
19752080 $('rec-download').hidden = !recorded;
19762081 $('rec-discard').hidden = !recorded;
19772082 if (recorded) {
1978- $('rec-download').textContent = `Download video (${fmtTime(recorded.seconds)}, ${fmtSize(recorded.blob.size)})`;
2083+ $('rec-download').textContent = `Download ${recorded.mime === 'audio/wav' ? 'WAV' : 'video'} (${fmtTime(recorded.seconds)}, ${fmtSize(recorded.blob.size)})`;
19792084 }
19802085 updateRecordingTime();
19812086 }
@@ -1985,17 +2090,19 @@ function updateRecordingTime() {
19852090 recMessage('');
19862091 return;
19872092 }
1988- const bytes = recording.chunks.reduce((n, c) => n + c.size, 0);
2093+ const bytes = recording.kind === 'audio' ? 44 + 4 * recording.frames : recording.chunks.reduce((n, c) => n + c.size, 0);
19892094 recMessage(`${fmtTime((performance.now() - recording.started) / 1000)} · ${fmtSize(bytes)}`);
19902095 }
19912096
19922097 function buildRecordingControls() {
19932098 const btn = $('record');
1994- if (!canRecord()) {
1995- btn.disabled = true;
1996- btn.title = 'Recording isn\'t supported in this browser';
1997- return;
1998- }
2099+ const kind = $('rec-kind');
2100+ try { if (['video', 'audio'].includes(localStorage.getItem(REC_KIND_KEY))) kind.value = localStorage.getItem(REC_KIND_KEY); } catch { /* storage blocked */ }
2101+ if (!canRecordVideo() && canRecordAudio()) kind.value = 'audio';
2102+ kind.addEventListener('change', () => {
2103+ try { localStorage.setItem(REC_KIND_KEY, kind.value); } catch { /* storage blocked */ }
2104+ renderRecording();
2105+ });
19992106 btn.addEventListener('click', () => (recording ? stopRecording() : startRecording()));
20002107 $('rec-download').addEventListener('click', saveRecording);
20012108 $('rec-discard').addEventListener('click', () => {
app/style.cssmodified+11−5View file
@@ -110,6 +110,7 @@ h2 {
110110 .rec-btn[aria-pressed="true"] { border-color: var(--rec); color: var(--rec); }
111111 .rec-btn[aria-pressed="true"] .rec-dot { border-radius: 2px; animation: rec-blink 1.2s steps(2, jump-none) infinite; }
112112 @keyframes rec-blink { 50% { opacity: 0.35; } }
113+.rec-kind { padding: 4px 6px; font-size: 13px; }
113114 .rec-status { font-size: 13px; color: var(--rec); font-variant-numeric: tabular-nums; white-space: nowrap; }
114115 .master-vol { display: flex; align-items: center; gap: 8px; width: 150px; }
115116 .master-vol output { font-size: 13px; color: var(--muted); font-variant-numeric: tabular-nums; min-width: 34px; text-align: right; }
@@ -231,11 +232,16 @@ button:disabled { cursor: default; opacity: 0.45; }
231232
232233 .trow {
233234 display: grid;
234- grid-template-columns: 22px 66px minmax(0, 1fr) 58px;
235+ grid-template-columns: 22px 62px minmax(0, 1fr) 44px;
235236 align-items: center;
236237 gap: 6px;
237238 }
238-.trow > select, .trow > .keys, .trow > .coords { grid-column: 3 / 5; }
239+.trow > select, .trow > .coords, .trow > .pair, .trow > .mono-check { grid-column: 3 / 5; }
240+/* the settings, two to a row where there's room */
241+.tgrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 7px 18px; }
242+.tgrid > .notes-editor { grid-column: 1 / -1; }
243+.pair { display: flex; gap: 4px; min-width: 0; }
244+.pair select { flex: 1 1 0; min-width: 0; }
239245 .trow .lbl { color: var(--muted); font-size: 13px; }
240246 .rate-row.custom > select { grid-column: 3; }
241247 .rate-row input[type="text"] {
@@ -252,6 +258,7 @@ button:disabled { cursor: default; opacity: 0.45; }
252258 .rate-row input.invalid { border-color: #d0453a; color: #d0453a; }
253259 .trow output { font-size: 12px; text-align: right; font-variant-numeric: tabular-nums; }
254260 .trow select { padding: 4px 6px; font-size: 13px; min-width: 0; }
261+.trow select:disabled { opacity: 0.45; }
255262 .trow input[type="range"] { accent-color: var(--c); }
256263 .trow.na > :not(.link) { opacity: 0.4; }
257264 .coords { font-size: 13px; font-variant-numeric: tabular-nums; }
@@ -272,9 +279,6 @@ button:disabled { cursor: default; opacity: 0.45; }
272279 .link:hover { opacity: 1; }
273280 .link[aria-pressed="true"] { color: var(--accent); opacity: 1; }
274281
275-.keys { display: grid; grid-template-columns: repeat(6, 1fr); gap: 3px; }
276-.keys button { padding: 2px 0; font-size: 12px; }
277-.keys button[aria-pressed="true"] { background: var(--c); border-color: var(--c); color: #fff; }
278282
279283 .link-note { display: flex; align-items: center; gap: 5px; margin: 2px 0 0; font-size: 12px; color: var(--muted); }
280284 .link-note svg { width: 13px; height: 13px; flex: none; color: var(--accent); }
@@ -406,6 +410,8 @@ button:disabled { cursor: default; opacity: 0.45; }
406410 .midi-btn[aria-pressed="true"] { background: var(--c); border-color: var(--c); color: #fff; }
407411 .notes-bar .check { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; color: var(--muted); cursor: pointer; }
408412 .notes-bar .check input { accent-color: var(--c); margin: 0; }
413+.mono-check { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; }
414+.mono-check input { accent-color: var(--c); margin: 0; }
409415 .notes-bar .quiet { margin-left: auto; }
410416 .notes-msg { margin: 0; font-size: 12px; color: var(--muted); line-height: 1.45; }
411417 .notes-msg .note-names { color: var(--fg); font-variant-numeric: tabular-nums; }