Files
JIANT/web/studio/audioedit.js
T
JUAN JIANTandClaude Opus 5.5 877df25a98 Studio: audio editor (RECORD space) (#290)
* Studio in six spaces (LISTEN, CREATE, RECORD, MANAGE, DEVICE, LEARN): a bar with their icons and names (at the bottom on a phone), each opening a sheet with its functions and what each does; the strip under it keeps that space's views; DEVICE's sheet holds the connection and what goes in and out (FM-1 or emulator, backup, export, import, audio); the heat palette on the bar and the sheets, and bytebeat scopes drawn live in the header and behind each sheet's title; a phone's selects never widen the page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UVqsRnhKjiABTzc6Ety3dd

* Studio RECORD › Audio editor: takes and audio files as clips on tracks (cut at the position, trim by the edges, move with a 1/16 snap at the BPM, fades, gain, normalize, reverse, duplicate, delete, undo and redo, mute, solo and level per track), played with WebAudio and rendered offline: the mix as a WAV, each track in a ZIP; a take's Edit button sends it there

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UVqsRnhKjiABTzc6Ety3dd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-30 13:23:36 +00:00

231 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant)
// JIANT Studio's audio editor: takes and audio files as clips on tracks, edited in the browser and mixed down. A clip is
// a window on a buffer (start on the timeline, offset into its buffer, length), with its gain, fades and direction; the
// buffers are never changed, so every edit can be undone. Moves and trims snap to a grid (a sixteenth at the BPM, or
// off). Playback: one AudioBufferSource per clip, its gain ramped for the fades; the mix and each track rendered offline
// to WAV. No DOM outside the element it is given; studio.js feeds it takes and files and gives it its words.
// const ed = new AudioEditor(root, words, { wav, zip });
// ed.addTake({ name, rate, planes, lanes: [{ name, color, pan }] }); ed.addFile(file)
const DB = (g) => Math.pow(10, g / 20);
export class AudioEditor {
constructor(root, L, lib) {
this.root = root; this.L = L; this.lib = lib;
this.tracks = []; this.sel = null; this.pps = 60; this.bpm = 120; this.snap = true; this.ph = 0;
this.undoS = []; this.redoS = []; this.ac = null; this.srcs = []; this.playing = false; this.t0 = 0; this.raf = 0; this.peaks = new Map();
this.build();
}
/* ---- the model */
get dur() { let d = 4; for (const t of this.tracks) for (const c of t.clips) d = Math.max(d, c.start + c.len); return d; }
snapT(x) { if (!this.snap) return Math.max(0, x); const g = 60 / this.bpm / 4; return Math.max(0, Math.round(x / g) * g); }
snapshot() { return JSON.stringify(this.tracks.map((t) => ({ ...t, clips: t.clips.map((c) => ({ ...c, buf: c.buf.id })) }))); }
bufs() { const m = new Map(); for (const t of this.tracks) for (const c of t.clips) m.set(c.buf.id, c.buf); return m; }
push() { this.undoS.push({ s: this.snapshot(), b: this.bufs() }); if (this.undoS.length > 80) this.undoS.shift(); this.redoS = []; }
restore(x) { const b = x.b; this.tracks = JSON.parse(x.s).map((t) => ({ ...t, clips: t.clips.map((c) => ({ ...c, buf: b.get(c.buf) })) })); this.sel = null; this.draw(); }
undo() { if (!this.undoS.length) return; this.redoS.push({ s: this.snapshot(), b: this.bufs() }); this.restore(this.undoS.pop()); this.say(this.L.undone); }
redo() { if (!this.redoS.length) return; this.undoS.push({ s: this.snapshot(), b: this.bufs() }); this.restore(this.redoS.pop()); }
buffer(planes, rate, name) { return { id: Math.random().toString(36).slice(2), planes, rate, name, secs: planes[0].length / rate }; }
addTake(tk) {
this.push();
const lanes = tk.lanes && tk.lanes.length === tk.planes.length ? tk.lanes : null;
if (!lanes || tk.planes.length <= 2) {
const b = this.buffer(tk.planes.slice(0, 2), tk.rate, tk.name);
this.tracks.push({ name: tk.name.replace(/^JIANT-/, "").slice(0, 22), color: "#a77bff", vol: 0, pan: 0, mute: false, solo: false, clips: [this.clip(b, 0)] });
} else tk.planes.forEach((p, i) => {
if (!p.some((v) => Math.abs(v) > 1e-4)) return; // a silent stem: no track
const b = this.buffer([p], tk.rate, `${tk.name} ${lanes[i].name}`);
this.tracks.push({ name: lanes[i].name, color: lanes[i].color || "#a77bff", vol: 0, pan: lanes[i].pan || 0, mute: false, solo: false, clips: [this.clip(b, 0)] });
});
this.fitZoom(); this.draw(); this.say(this.L.added.replace("%s", tk.name));
}
async addFile(f) {
const ac = this.ctx(), ab = await ac.decodeAudioData(await f.arrayBuffer());
const planes = Array.from({ length: Math.min(2, ab.numberOfChannels) }, (_, k) => ab.getChannelData(k).slice());
this.push();
this.tracks.push({ name: f.name.replace(/\.[^.]+$/, "").slice(0, 22), color: "#ff8a1f", vol: 0, pan: 0, mute: false, solo: false, clips: [this.clip(this.buffer(planes, ab.sampleRate, f.name), this.ph)] });
this.fitZoom(); this.draw(); this.say(this.L.added.replace("%s", f.name));
}
clip(buf, start) { return { buf, start, off: 0, len: buf.secs, gain: 0, fin: 0, fout: 0, rev: false }; }
selClip() { const s = this.sel; return s ? this.tracks[s.t] && this.tracks[s.t].clips[s.c] : null; }
/* ---- the edits (each one undoable) */
edit(f) { const c = this.selClip(); if (!c) { this.say(this.L.pick); return; } this.push(); f(c, this.tracks[this.sel.t]); this.draw(); }
split() {
this.edit((c, t) => {
const at = this.ph - c.start; if (at <= 0.01 || at >= c.len - 0.01) { this.undoS.pop(); this.say(this.L.splitHere); return; }
const b = { ...c, start: this.ph, off: c.rev ? c.off : c.off + at, len: c.len - at, fin: 0 };
if (c.rev) c.off = c.off + (c.len - at);
c.len = at; c.fout = 0; t.clips.splice(this.sel.c + 1, 0, b);
});
}
del() { this.edit((c, t) => { t.clips.splice(this.sel.c, 1); this.sel = null; }); }
dup() { this.edit((c, t) => { t.clips.push({ ...c, start: this.snapT(c.start + c.len) }); this.sel = { t: this.sel.t, c: t.clips.length - 1 }; }); }
reverse() { this.edit((c) => { c.rev = !c.rev; }); }
normalize() {
this.edit((c) => {
let pk = 0; const r = c.buf.rate, a = Math.floor(c.off * r), n = Math.floor(c.len * r);
for (const p of c.buf.planes) for (let i = a; i < a + n && i < p.length; i++) pk = Math.max(pk, Math.abs(p[i]));
if (pk > 1e-6) c.gain = Math.round(20 * Math.log10(0.966 / pk) * 10) / 10;
});
}
set(k, v) { this.edit((c) => { c[k] = v; }); }
/* ---- the view */
build() {
const h = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
this.h = h; this.root.replaceChildren(); this.root.classList.add("aed");
const tools = h("div", "aedtools"), L = this.L;
const B = (txt, f, k) => { const b = h("button", "aedbtn", txt); b.type = "button"; b.onclick = f; if (k) b.title = k; tools.append(b); return b; };
this.playB = B("▶", () => (this.playing ? this.stop() : this.play()), "Espacio");
B("■", () => { this.stop(); this.ph = 0; this.draw(); });
B("✂ " + L.split, () => this.split(), "S"); B(L.dup, () => this.dup(), "D"); B(L.rev, () => this.reverse()); B(L.norm, () => this.normalize());
B("⌫ " + L.del, () => this.del(), "Supr"); B("↶", () => this.undo(), "Ctrl+Z"); B("↷", () => this.redo(), "Ctrl+Shift+Z");
B("−", () => { this.pps = Math.max(8, this.pps / 1.5); this.draw(); }); B("+", () => { this.pps = Math.min(600, this.pps * 1.5); this.draw(); });
const snap = B(L.snap + ": 1/16", () => { this.snap = !this.snap; snap.textContent = `${L.snap}: ${this.snap ? "1/16" : "—"}`; });
const bpm = h("input"); bpm.type = "number"; bpm.min = 40; bpm.max = 240; bpm.value = this.bpm; bpm.className = "aedbpm"; bpm.setAttribute("aria-label", "BPM");
bpm.onchange = () => { this.bpm = Math.max(40, Math.min(240, +bpm.value || 120)); this.draw(); }; tools.append(bpm, h("span", "aeddim", "BPM"));
this.scroll = h("div", "aedscroll"); this.grid = h("div", "aedgrid"); this.scroll.append(this.grid);
this.insp = h("div", "aedinsp"); this.status = h("p", "aedstat"); this.foot = h("div", "aedfoot");
this.clock = h("b", "aedclock", "00:00.0");
const ex = (txt, f) => { const b = h("button", "btn", txt); b.type = "button"; b.onclick = f; return b; };
this.foot.append(this.clock, ex(L.expMix, () => this.exportMix()), ex(L.expTracks, () => this.exportTracks()));
this.empty = h("p", "aeddim aedempty", L.empty);
this.root.append(tools, this.empty, this.scroll, this.insp, this.foot, this.status);
this.root.tabIndex = 0;
this.root.addEventListener("keydown", (e) => {
if (e.target.tagName === "INPUT") return;
const k = e.key.toLowerCase();
if (k === " ") { e.preventDefault(); this.playing ? this.stop() : this.play(); }
else if (k === "s") this.split(); else if (k === "d") this.dup(); else if (k === "delete" || k === "backspace") { e.preventDefault(); this.del(); }
else if (k === "z" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); e.shiftKey ? this.redo() : this.undo(); }
});
new ResizeObserver(() => this.draw()).observe(this.scroll);
this.draw();
}
fitZoom() { const w = (this.scroll.clientWidth || 600) - 120; this.pps = Math.max(8, Math.min(200, w / (this.dur + 1))); }
say(s) { this.status.textContent = s; }
peaksOf(buf) {
if (this.peaks.has(buf.id)) return this.peaks.get(buf.id);
const p = buf.planes[0], q = buf.planes[1] || p, step = Math.max(1, Math.floor(buf.rate / 400)), n = Math.ceil(p.length / step), out = new Float32Array(n);
for (let i = 0; i < n; i++) { let m = 0; for (let j = i * step, e = Math.min(p.length, j + step); j < e; j++) m = Math.max(m, Math.abs(p[j]), Math.abs(q[j])); out[i] = m; }
this.peaks.set(buf.id, { out, per: step / buf.rate }); return this.peaks.get(buf.id);
}
draw() {
if (!this.grid) return;
const h = this.h, HEAD = 110, W = Math.max(this.scroll.clientWidth - HEAD, (this.dur + 2) * this.pps), beat = 60 / this.bpm;
this.empty.hidden = !!this.tracks.length; this.scroll.hidden = !this.tracks.length; this.insp.hidden = this.foot.hidden = !this.tracks.length;
this.grid.style.width = `${HEAD + W}px`; this.grid.replaceChildren();
const ruler = h("div", "aedruler"); ruler.style.width = `${W}px`; ruler.style.marginLeft = `${HEAD}px`;
const barW = beat * 4 * this.pps, every = barW < 40 ? Math.ceil(40 / barW) : 1;
for (let b = 0; b * beat * 4 < this.dur + 2; b += every) { const m = h("span", null, String(b + 1)); m.style.left = `${b * beat * 4 * this.pps}px`; ruler.append(m); }
ruler.onpointerdown = (e) => { const r = ruler.getBoundingClientRect(); this.ph = this.snapT((e.clientX - r.left) / this.pps); if (this.playing) { this.stop(); this.play(); } this.draw(); };
this.grid.append(ruler);
const solo = this.tracks.some((t) => t.solo);
this.tracks.forEach((t, ti) => {
const row = h("div", "aedrow"), head = h("div", "aedhead"), lane = h("div", "aedlane");
head.style.setProperty("--c", t.color);
const nm = h("b", null, t.name), ms = h("div", "aedms"), M = h("button", null, "M"), S = h("button", null, "S"), vol = h("input");
M.type = S.type = "button"; M.setAttribute("aria-pressed", String(t.mute)); S.setAttribute("aria-pressed", String(t.solo));
M.onclick = () => { t.mute = !t.mute; this.draw(); this.remix(); }; S.onclick = () => { t.solo = !t.solo; this.draw(); this.remix(); };
vol.type = "range"; vol.min = -30; vol.max = 6; vol.step = 0.5; vol.value = t.vol; vol.setAttribute("aria-label", `${t.name} dB`); vol.oninput = () => { t.vol = +vol.value; this.remix(); };
ms.append(M, S); head.append(nm, ms, vol); lane.style.width = `${W}px`;
if (t.mute || (solo && !t.solo)) row.classList.add("off");
for (let b = 0; b * beat < this.dur + 2; b++) { const g = h("i", b % 4 ? "beat" : "bar"); g.style.left = `${b * beat * this.pps}px`; lane.append(g); }
t.clips.forEach((c, ci) => lane.append(this.clipEl(t, ti, c, ci)));
lane.onpointerdown = (e) => { if (e.target !== lane) return; this.sel = null; const r = lane.getBoundingClientRect(); this.ph = this.snapT((e.clientX - r.left) / this.pps); this.draw(); };
row.append(head, lane); this.grid.append(row);
});
this.phEl = h("div", "aedph"); this.phEl.style.left = `${HEAD + this.ph * this.pps}px`; this.grid.append(this.phEl);
this.clockSet(this.ph); this.drawInsp();
}
clipEl(t, ti, c, ci) {
const h = this.h, el = h("div", "aedclip"), cv = h("canvas"), lb = h("span", null, c.buf.name.split(" ").pop());
const sel = this.sel && this.sel.t === ti && this.sel.c === ci;
el.style.cssText = `left:${c.start * this.pps}px;width:${Math.max(4, c.len * this.pps)}px;--c:${t.color}`; if (sel) el.classList.add("sel");
const wpx = Math.max(4, Math.round(c.len * this.pps)); cv.width = Math.min(4000, wpx); cv.height = 56;
const g = cv.getContext("2d"), P = this.peaksOf(c.buf), gain = DB(c.gain); g.fillStyle = t.color;
for (let x = 0; x < cv.width; x++) {
const tt = (x / cv.width) * c.len, src = c.rev ? c.off + c.len - tt : c.off + tt, i = Math.floor(src / P.per);
let env = 1; if (c.fin && tt < c.fin) env = tt / c.fin; if (c.fout && tt > c.len - c.fout) env = (c.len - tt) / c.fout;
const a = Math.min(1, (P.out[i] || 0) * gain * env) * 26; g.fillRect(x, 28 - a, 1, a * 2 || 1);
}
if (c.fin) { const f = h("i", "fin"); f.style.width = `${c.fin * this.pps}px`; el.append(f); }
if (c.fout) { const f = h("i", "fout"); f.style.width = `${c.fout * this.pps}px`; el.append(f); }
const tl = h("i", "trim l"), tr = h("i", "trim r");
el.append(cv, lb, tl, tr);
const drag = (e, mode) => {
e.stopPropagation(); e.preventDefault(); this.sel = { t: ti, c: ci }; const x0 = e.clientX, s0 = { ...c }; let moved = false;
const mv = (ev) => {
const dt = (ev.clientX - x0) / this.pps; if (!moved && Math.abs(ev.clientX - x0) < 3) return; if (!moved) { this.push(); moved = true; }
if (mode === "move") c.start = this.snapT(s0.start + dt);
else if (mode === "l") { const ns = Math.min(s0.start + s0.len - 0.02, this.snapT(s0.start + dt)), d = ns - s0.start; const lim = c.rev ? 0 : -s0.off; const dd = Math.max(d, lim, -s0.start); c.start = s0.start + dd; c.len = s0.len - dd; if (!c.rev) c.off = s0.off + dd; }
else { const end = this.snapT(s0.start + s0.len + dt), max = c.rev ? s0.off + s0.len : c.buf.secs - s0.off; c.len = Math.max(0.02, Math.min(end - s0.start, c.rev ? s0.len + s0.off : max)); if (c.rev) c.off = Math.max(0, s0.off + s0.len - c.len); }
el.style.left = `${c.start * this.pps}px`; el.style.width = `${c.len * this.pps}px`;
};
const up = () => { removeEventListener("pointermove", mv); removeEventListener("pointerup", up); this.draw(); };
addEventListener("pointermove", mv); addEventListener("pointerup", up);
};
el.onpointerdown = (e) => drag(e, "move"); tl.onpointerdown = (e) => drag(e, "l"); tr.onpointerdown = (e) => drag(e, "r");
return el;
}
drawInsp() {
const h = this.h, c = this.selClip(), L = this.L; this.insp.replaceChildren();
if (!c) { this.insp.append(h("p", "aeddim", L.pickHelp)); return; }
const k = (lab, key, min, max, step, unit) => {
const w = h("label", "aedk"), i = h("input"), o = h("b", null, `${c[key]}${unit}`);
i.type = "range"; i.min = min; i.max = max; i.step = step; i.value = c[key];
i.onpointerdown = () => this.push(); i.oninput = () => { c[key] = +i.value; o.textContent = `${c[key]}${unit}`; this.drawLane(); };
w.append(h("span", null, lab), o, i); return w;
};
const t = this.tracks[this.sel.t];
this.insp.append(h("p", "aedclipn", `${t.name} · ${c.buf.name.split(" ").pop()} · ${c.start.toFixed(2)} s → ${(c.start + c.len).toFixed(2)} s${c.rev ? " · ⇆" : ""}`),
k(L.gain, "gain", -24, 12, 0.5, " dB"), k(L.fin, "fin", 0, Math.min(4, c.len / 2), 0.01, " s"), k(L.fout, "fout", 0, Math.min(4, c.len / 2), 0.01, " s"));
}
drawLane() { clearTimeout(this.dl); this.dl = setTimeout(() => { const keep = this.insp; this.draw(); }, 60); }
clockSet(s) { const m = Math.floor(s / 60), r = s - m * 60; this.clock.textContent = `${String(m).padStart(2, "0")}:${r.toFixed(1).padStart(4, "0")}`; }
/* ---- sound */
ctx() { return this.ac || (this.ac = new AudioContext()); }
abuf(ac, c) { // the clip's window as an AudioBuffer (reversed if so)
const r = c.buf.rate, a = Math.floor(c.off * r), n = Math.max(1, Math.floor(c.len * r)), b = ac.createBuffer(c.buf.planes.length, n, r);
c.buf.planes.forEach((p, k) => { const d = b.getChannelData(k); d.set(p.subarray(a, a + n)); if (c.rev) d.reverse(); });
return b;
}
schedule(ac, dest, from, when) {
const solo = this.tracks.some((t) => t.solo), out = [];
for (const t of this.tracks) {
const tg = ac.createGain(), pan = ac.createStereoPanner(); tg.gain.value = t.mute || (solo && !t.solo) ? 0 : DB(t.vol); pan.pan.value = t.pan || 0;
tg.connect(pan).connect(dest); out.push({ t, tg });
for (const c of t.clips) {
const end = c.start + c.len; if (end <= from) continue;
const s = ac.createBufferSource(), g = ac.createGain(), into = Math.max(0, from - c.start), at = when + Math.max(0, c.start - from), v = DB(c.gain);
s.buffer = this.abuf(ac, c); s.connect(g).connect(tg);
g.gain.setValueAtTime(c.fin && into < c.fin ? v * into / c.fin : v, at);
if (c.fin && into < c.fin) g.gain.linearRampToValueAtTime(v, at + (c.fin - into));
if (c.fout) { const fs = Math.max(at, at + (c.len - c.fout - into)); g.gain.setValueAtTime(v, fs); g.gain.linearRampToValueAtTime(0, at + (c.len - into)); }
s.start(at, into); this.srcs.push(s);
}
}
return out;
}
play() {
const ac = this.ctx(); ac.resume(); this.srcs = []; this.mixers = this.schedule(ac, ac.destination, this.ph, ac.currentTime + 0.05);
this.playing = true; this.t0 = ac.currentTime + 0.05 - this.ph; this.playB.textContent = "❚❚";
const tick = () => { if (!this.playing) return; const p = ac.currentTime - this.t0; this.phEl.style.left = `${110 + p * this.pps}px`; this.clockSet(p); if (p > this.dur + 0.2) { this.stop(); return; } this.raf = requestAnimationFrame(tick); };
tick();
}
stop() { if (!this.playing) return; this.ph = Math.max(0, this.ctx().currentTime - this.t0); for (const s of this.srcs) { try { s.stop(); } catch (_) {} } this.srcs = []; this.playing = false; this.playB.textContent = "▶"; cancelAnimationFrame(this.raf); this.draw(); }
remix() { if (!this.mixers) return; const solo = this.tracks.some((t) => t.solo); for (const m of this.mixers) m.tg.gain.value = m.t.mute || (solo && !m.t.solo) ? 0 : DB(m.t.vol); }
async render(only) {
const rate = 44100, n = Math.ceil(this.dur * rate) + 1, oc = new OfflineAudioContext(2, n, rate), keep = this.tracks;
if (only) this.tracks = [{ ...only, mute: false, solo: false }];
try { this.schedule(oc, oc.destination, 0, 0); } finally { this.tracks = keep; }
const b = await oc.startRendering(); return [b.getChannelData(0), b.getChannelData(1)];
}
save(blob, name) { const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = name; document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 4000); }
async exportMix() { if (!this.tracks.length) return; this.say(this.L.rendering); const p = await this.render(); this.save(new Blob([this.lib.wav(p, 44100)], { type: "audio/wav" }), "jiant-mix.wav"); this.say(this.L.exported); }
async exportTracks() {
if (!this.tracks.length) return; this.say(this.L.rendering); const files = [];
for (const [i, t] of this.tracks.entries()) files.push({ name: `jiant-tracks/${String(i + 1).padStart(2, "0")}-${t.name.replace(/[^\w-]+/g, "_")}.wav`, data: this.lib.wav(await this.render(t), 44100) });
files.push({ name: "jiant-tracks/MIX.wav", data: this.lib.wav(await this.render(), 44100) });
this.save(new Blob([this.lib.zip(files)], { type: "application/zip" }), "jiant-tracks.zip"); this.say(this.L.exported);
}
}