// Live spectrogram of a sound: the newest spectrum at the right, scrolling // left, over the last SPEC_SECONDS. Spectra come from an AnalyserNode with a // SPEC_FFT-point window (11.7 Hz frequency bins at 48 kHz), shown up to // SPEC_FMAX, a little above the frequency slider's 2000 Hz so a line there is // not cut off. Levels are in dB: SPEC_TOP_DB (a little above a full-scale // tone) is the darkest, fading to white SPEC_RANGE_DB below that. It scrolls // only while sound plays, and keeps its picture when stopped. import { color, prepare } from './canvas.js'; export const SPEC_FFT = 4096; const SPEC_FMAX = 2100; const SPEC_SECONDS = 4; const SPEC_COLUMNS_PER_SECOND = 60; const SPEC_TOP_DB = -10; const SPEC_RANGE_DB = 70; // White (quiet) through the accent blue to navy (loud). The slides keep their // light colors in both themes, so these are fixed. const SPEC_COLORS = [[255, 255, 255], [83, 126, 186], [28, 41, 84]]; function specColor(t) { const s = Math.max(0, Math.min(1, t)) * (SPEC_COLORS.length - 1); const i = Math.min(Math.floor(s), SPEC_COLORS.length - 2); const u = s - i; return SPEC_COLORS[i].map((c, j) => c + u * (SPEC_COLORS[i + 1][j] - c)); } // attach(analyser) starts scrolling with a playing sound, detach() stops it; // draw() redraws (after resizing, or showing the canvas). export function createSpectrogram(canvas) { const columns = SPEC_SECONDS * SPEC_COLUMNS_PER_SECOND; let rate = 0; let bins = 0; let image = null; // columns x bins, low frequencies at the bottom let analyser = null; let spectrum = null; let lastTime = null; let rafId = null; let started = false; const off = document.createElement('canvas'); function setRate(r) { if (r === rate) return; rate = r; bins = Math.ceil((SPEC_FMAX * SPEC_FFT) / rate); image = new ImageData(columns, bins); image.data.fill(255); } setRate(48000); // Shift the image left by n columns and fill them with the current spectrum. function addColumns(n) { n = Math.min(n, columns); analyser.getFloatFrequencyData(spectrum); const data = image.data; const rowBytes = 4 * columns; for (let k = 0; k < bins; k++) { const row = (bins - 1 - k) * rowBytes; data.copyWithin(row, row + 4 * n, row + rowBytes); const [r, g, b] = specColor(1 + (spectrum[k] - SPEC_TOP_DB) / SPEC_RANGE_DB); for (let c = columns - n; c < columns; c++) { const o = row + 4 * c; data[o] = r; data[o + 1] = g; data[o + 2] = b; } } } function tick() { const t = analyser.context.currentTime; lastTime ??= t; const n = Math.floor((t - lastTime) * SPEC_COLUMNS_PER_SECOND); if (n > 0) { lastTime += n / SPEC_COLUMNS_PER_SECOND; addColumns(n); draw(); } rafId = requestAnimationFrame(tick); } function attach(a) { detach(); setRate(a.context.sampleRate); analyser = a; spectrum = new Float32Array(a.frequencyBinCount); lastTime = null; started = true; rafId = requestAnimationFrame(tick); } function detach() { cancelAnimationFrame(rafId); analyser = null; } function draw() { if (canvas.hidden || !canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const fg = color('--fg'); const left = 56; const right = 10; const top = 8; const bottom = 30; const pw = w - left - right; const ph = h - top - bottom; off.width = columns; off.height = bins; off.getContext('2d').putImageData(image, 0, 0); ctx.imageSmoothingEnabled = true; ctx.drawImage(off, left, top, pw, ph); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1; ctx.strokeRect(left, top, pw, ph); ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif'; if (!started) { ctx.globalAlpha = 0.6; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('Press Play to see the spectrum of the sound', left + pw / 2, top + ph / 2); ctx.globalAlpha = 1; } // time before now, with now at the right edge ctx.textAlign = 'center'; ctx.textBaseline = 'top'; for (let sec = 0; sec <= SPEC_SECONDS; sec++) { const x = left + pw - (sec / SPEC_SECONDS) * pw; ctx.beginPath(); ctx.moveTo(x, top + ph); ctx.lineTo(x, top + ph + 4); ctx.stroke(); ctx.fillText(sec === 0 ? 'now' : `−${sec} s`, x, top + ph + 7); } const fTop = (bins * rate) / SPEC_FFT; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; for (let f = 0; f <= SPEC_FMAX; f += 500) { const y = top + ph - (f / fTop) * ph; ctx.beginPath(); ctx.moveTo(left - 4, y); ctx.lineTo(left, y); ctx.stroke(); ctx.fillText(`${f} Hz`, left - 7, y); } } return { attach, detach, draw }; }