Files
2026-11-01 14:48:09 +01:00

319 lines
10 KiB
JavaScript

"use strict";
const BINS = 2000; // Auflösung der vorberechneten Pegelwerte pro Datei
const BAR_W = 3; // Balkenbreite in CSS-Pixeln
const BAR_GAP = 2; // Abstand zwischen Balken
const SEEK_STEP = 5; // Sekunden für Pfeiltasten
/** Maximaler Betrag (Spitzenpegel) pro Abschnitt, über alle Kanäle. */
function computePeaks(buffer) {
const bins = new Float32Array(BINS);
const n = buffer.length;
const step = n / BINS;
for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
const data = buffer.getChannelData(ch);
for (let i = 0; i < BINS; i++) {
const s = Math.floor(i * step);
const e = Math.min(n, Math.floor((i + 1) * step));
let max = 0;
for (let j = s; j < e; j++) {
const v = Math.abs(data[j]);
if (v > max) max = v;
}
if (max > bins[i]) bins[i] = max;
}
}
return bins;
}
function fmt(t) {
t = Math.max(0, Math.floor(t));
return Math.floor(t / 60) + ":" + String(t % 60).padStart(2, "0");
}
function drawBar(g, x, y, w, h) {
g.beginPath();
if (g.roundRect) g.roundRect(x, y, w, h, w / 2);
else g.rect(x, y, w, h);
g.fill();
}
class ABPlayer {
constructor(root) {
this.root = root;
this.tracks = [...root.querySelectorAll(".track")];
this.canvases = this.tracks.map(t => t.querySelector("canvas"));
this.labels = this.tracks.map(t => t.querySelector(".track-label"));
this.playBtn = root.querySelector(".play");
this.timeEl = root.querySelector(".time");
this.statusEl = root.querySelector(".status");
this.toggleBtn = root.querySelector(".toggle");
this.ctx = null;
this.buffers = [null, null];
this.peaks = [null, null];
this.bars = [[], []];
this.norm = 1;
this.sources = [];
this.gains = [];
this.active = 0;
this.playing = false;
this.ready = false;
this.offset = 0;
this.startedAt = 0;
this.duration = 0;
this.raf = 0;
this.tick = this.tick.bind(this);
this.playBtn.addEventListener("click", () => this.toggle());
this.labels.forEach((btn, i) => btn.addEventListener("click", () => this.switchTo(i)));
this.canvases.forEach((cv, i) => cv.addEventListener("pointerdown", e => this.onCanvasPointer(e, i)));
document.addEventListener("keydown", e => this.onKey(e));
new ResizeObserver(() => { this.layout(); this.draw(); }).observe(root);
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => this.draw());
this.toggleBtn.addEventListener("click", () => this.toggleAB());
this.refreshUI();
}
// --- Laden ---------------------------------------------------------------
async load(urlA, urlB) {
this.reset();
this.root.classList.add("is-loading");
this.setStatus("Audio wird geladen …");
const ctx = this.ctx || (this.ctx = new (window.AudioContext || window.webkitAudioContext)());
try {
this.buffers = await Promise.all([urlA, urlB].map(async url => {
const res = await fetch(url);
if (!res.ok) throw new Error("HTTP " + res.status);
return ctx.decodeAudioData(await res.arrayBuffer());
}));
} catch (err) {
this.root.classList.remove("is-loading");
this.setStatus("Audio konnte nicht geladen werden.");
throw err;
}
this.peaks = this.buffers.map(computePeaks);
// Gemeinsame Normierung, damit Pegelunterschiede zwischen A und B sichtbar bleiben
const globalMax = Math.max(...this.peaks.map(p => p.reduce((m, v) => Math.max(m, v), 0)));
this.norm = globalMax > 0 ? 1 / globalMax : 1;
this.duration = Math.max(...this.buffers.map(b => b.duration));
this.ready = true;
this.root.classList.remove("is-loading");
this.setStatus("");
this.layout();
this.refreshUI();
}
reset() {
cancelAnimationFrame(this.raf);
this.stopSources();
this.playing = false;
this.ready = false;
this.offset = 0;
this.active = 0;
this.buffers = [null, null];
this.bars = [[], []];
this.refreshUI();
}
// --- Wiedergabe ------------------------------------------------------------
position() {
if (!this.playing) return this.offset;
const elapsed = Math.max(0, this.ctx.currentTime - this.startedAt);
return Math.min(this.duration, this.offset + elapsed);
}
startSources() {
const ctx = this.ctx;
this.stopSources();
this.sources = this.buffers.map((buf, i) => {
const src = ctx.createBufferSource();
src.buffer = buf;
const gain = ctx.createGain();
gain.gain.value = i === this.active ? 1 : 0;
src.connect(gain).connect(ctx.destination);
this.gains[i] = gain;
return src;
});
// Beide Quellen starten gleichzeitig und laufen stumm bzw. hörbar parallel.
// Umschalten ändert nur die Lautstärke, daher ohne Lücke und exakt synchron.
const when = ctx.currentTime + 0.02;
this.sources.forEach(s => s.start(when, this.offset));
this.startedAt = when;
}
stopSources() {
this.sources.forEach(s => { try { s.stop(); s.disconnect(); } catch (_) {} });
this.sources = [];
}
async play() {
if (!this.ready) return;
await this.ctx.resume();
if (this.offset >= this.duration) this.offset = 0;
this.startSources();
this.playing = true;
this.refreshUI();
this.raf = requestAnimationFrame(this.tick);
}
pause() {
if (!this.playing) return;
this.offset = this.position();
this.stopSources();
this.playing = false;
cancelAnimationFrame(this.raf);
this.refreshUI();
}
toggle() { this.playing ? this.pause() : this.play(); }
seek(t) {
if (!this.ready) return;
this.offset = Math.min(Math.max(0, t), this.duration);
if (this.playing) this.startSources();
this.refreshUI();
}
switchTo(i) {
if (!this.ready || i === this.active) return;
this.active = i;
if (this.playing) {
const now = this.ctx.currentTime;
this.gains.forEach((g, k) => {
g.gain.cancelScheduledValues(now);
g.gain.setTargetAtTime(k === i ? 1 : 0, now, 0.005); // kurze Rampe gegen Knacken
});
}
this.refreshUI();
}
toggleAB() { this.switchTo(1 - this.active); }
tick() {
if (!this.playing) return;
if (this.position() >= this.duration) {
this.pause();
this.offset = 0;
this.refreshUI();
return;
}
this.refreshUI();
this.raf = requestAnimationFrame(this.tick);
}
// --- Eingaben --------------------------------------------------------------
onCanvasPointer(e, i) {
if (!this.ready) return;
if (i !== this.active) {
this.switchTo(i); // Klick auf die andere Spur: wechseln, gleiche Stelle
} else {
const rect = this.canvases[i].getBoundingClientRect();
this.seek((e.clientX - rect.left) / rect.width * this.duration);
}
}
onKey(e) {
if (!this.ready) return;
const t = e.target;
const isRadio = t.matches('input[type="radio"]');
if (t.closest("textarea, select, input:not([type=radio])")) return;
if (isRadio && (e.key === " " || e.key.startsWith("Arrow"))) return;
if ((e.key === " " || e.key === "Enter") && t.closest("button")) return;
if (e.key === " ") { e.preventDefault(); this.toggle(); }
else if (e.key === "a" || e.key === "A") this.switchTo(0);
else if (e.key === "b" || e.key === "B") this.switchTo(1);
else if (e.key === "ArrowLeft") { e.preventDefault(); this.seek(this.position() - SEEK_STEP); }
else if (e.key === "ArrowRight") { e.preventDefault(); this.seek(this.position() + SEEK_STEP); }
else if (e.key === "t" || e.key === "T") this.toggleAB();
}
// --- Darstellung -----------------------------------------------------------
setStatus(msg) { this.statusEl.textContent = msg; }
/** Balkenhöhen für die aktuelle Breite berechnen. */
layout() {
if (!this.ready) return;
this.canvases.forEach((cv, i) => {
const w = cv.clientWidth;
const n = Math.max(1, Math.floor((w + BAR_GAP) / (BAR_W + BAR_GAP)));
const buf = this.buffers[i];
const peaks = this.peaks[i];
const bars = new Array(n);
for (let k = 0; k < n; k++) {
const b0 = Math.floor((k / n) * this.duration / buf.duration * BINS);
const b1 = Math.floor(((k + 1) / n) * this.duration / buf.duration * BINS);
let max = 0;
for (let b = b0; b < Math.min(BINS, Math.max(b1, b0 + 1)); b++) {
if (peaks[b] > max) max = peaks[b];
}
bars[k] = max * this.norm;
}
this.bars[i] = bars;
});
}
refreshUI() {
this.root.classList.toggle("is-playing", this.playing);
this.playBtn.disabled = !this.ready;
this.playBtn.setAttribute("aria-label", this.playing ? "Pause" : "Abspielen");
this.toggleBtn.disabled = !this.ready;
this.tracks.forEach((el, i) => {
el.classList.toggle("is-active", i === this.active);
this.labels[i].setAttribute("aria-pressed", String(i === this.active));
});
this.timeEl.textContent = fmt(this.position()) + " / " + fmt(this.duration);
this.draw();
}
draw() {
const dpr = window.devicePixelRatio || 1;
const cs = getComputedStyle(this.root);
const accent = cs.getPropertyValue("--accent").trim() || "#2563eb";
const muted = cs.getPropertyValue("--muted").trim() || "#888";
const text = cs.getPropertyValue("--text").trim() || "#000";
const progress = this.duration ? this.position() / this.duration : 0;
this.canvases.forEach((cv, i) => {
const w = cv.clientWidth, h = cv.clientHeight;
if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(h * dpr)) {
cv.width = Math.round(w * dpr);
cv.height = Math.round(h * dpr);
}
const g = cv.getContext("2d");
g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.clearRect(0, 0, w, h);
const bars = this.bars[i];
const isActive = i === this.active;
const n = bars.length;
if (!n) return;
const total = n * BAR_W + (n - 1) * BAR_GAP;
const x0 = (w - total) / 2;
for (let k = 0; k < n; k++) {
const played = (k + 0.5) / n <= progress;
g.fillStyle = played ? accent : muted;
g.globalAlpha = played ? (isActive ? 1 : 0.4) : (isActive ? 0.55 : 0.25);
const bh = Math.max(2, bars[k] * h * 0.92);
drawBar(g, x0 + k * (BAR_W + BAR_GAP), (h - bh) / 2, BAR_W, bh);
}
// Abspielposition
g.globalAlpha = isActive ? 0.9 : 0.3;
g.fillStyle = text;
g.fillRect(Math.min(w - 1, x0 + progress * total), 0, 1.5, h);
g.globalAlpha = 1;
});
}
}