/ interactive_tutorials / hardening_softening
Sign in
interactive_tutorials / hardening_softening
hardening_softening / app / js / spectrogram.js
154 lines · 4.7 KBCodeBlameHistory
7212d95Hardening and softening tutorialJeremy Magland 1// Live spectrogram of a sound: the newest spectrum at the right, scrolling
2// left, over the last SPEC_SECONDS. Spectra come from an AnalyserNode with a
3// SPEC_FFT-point window (11.7 Hz frequency bins at 48 kHz), shown up to
4// SPEC_FMAX, a little above the frequency slider's 2000 Hz so a line there is
5// not cut off. Levels are in dB: SPEC_TOP_DB (a little above a full-scale
6// tone) is the darkest, fading to white SPEC_RANGE_DB below that. It scrolls
7// only while sound plays, and keeps its picture when stopped.
9import { color, prepare } from './canvas.js';
11export const SPEC_FFT = 4096;
12const SPEC_FMAX = 2100;
13const SPEC_SECONDS = 4;
14const SPEC_COLUMNS_PER_SECOND = 60;
15const SPEC_TOP_DB = -10;
16const SPEC_RANGE_DB = 70;
18// White (quiet) through the accent blue to navy (loud). The slides keep their
19// light colors in both themes, so these are fixed.
20const SPEC_COLORS = [[255, 255, 255], [83, 126, 186], [28, 41, 84]];
22function specColor(t) {
23 const s = Math.max(0, Math.min(1, t)) * (SPEC_COLORS.length - 1);
24 const i = Math.min(Math.floor(s), SPEC_COLORS.length - 2);
25 const u = s - i;
26 return SPEC_COLORS[i].map((c, j) => c + u * (SPEC_COLORS[i + 1][j] - c));
29// attach(analyser) starts scrolling with a playing sound, detach() stops it;
30// draw() redraws (after resizing, or showing the canvas).
31export function createSpectrogram(canvas) {
32 const columns = SPEC_SECONDS * SPEC_COLUMNS_PER_SECOND;
33 let rate = 0;
34 let bins = 0;
35 let image = null; // columns x bins, low frequencies at the bottom
36 let analyser = null;
37 let spectrum = null;
38 let lastTime = null;
39 let rafId = null;
40 let started = false;
41 const off = document.createElement('canvas');
43 function setRate(r) {
44 if (r === rate) return;
45 rate = r;
46 bins = Math.ceil((SPEC_FMAX * SPEC_FFT) / rate);
47 image = new ImageData(columns, bins);
48 image.data.fill(255);
49 }
50 setRate(48000);
52 // Shift the image left by n columns and fill them with the current spectrum.
53 function addColumns(n) {
54 n = Math.min(n, columns);
55 analyser.getFloatFrequencyData(spectrum);
56 const data = image.data;
57 const rowBytes = 4 * columns;
58 for (let k = 0; k < bins; k++) {
59 const row = (bins - 1 - k) * rowBytes;
60 data.copyWithin(row, row + 4 * n, row + rowBytes);
61 const [r, g, b] = specColor(1 + (spectrum[k] - SPEC_TOP_DB) / SPEC_RANGE_DB);
62 for (let c = columns - n; c < columns; c++) {
63 const o = row + 4 * c;
64 data[o] = r;
65 data[o + 1] = g;
66 data[o + 2] = b;
67 }
68 }
69 }
71 function tick() {
72 const t = analyser.context.currentTime;
73 lastTime ??= t;
74 const n = Math.floor((t - lastTime) * SPEC_COLUMNS_PER_SECOND);
75 if (n > 0) {
76 lastTime += n / SPEC_COLUMNS_PER_SECOND;
77 addColumns(n);
78 draw();
79 }
80 rafId = requestAnimationFrame(tick);
81 }
83 function attach(a) {
84 detach();
85 setRate(a.context.sampleRate);
86 analyser = a;
87 spectrum = new Float32Array(a.frequencyBinCount);
88 lastTime = null;
89 started = true;
90 rafId = requestAnimationFrame(tick);
91 }
93 function detach() {
94 cancelAnimationFrame(rafId);
95 analyser = null;
96 }
98 function draw() {
99 if (canvas.hidden || !canvas.clientWidth) return;
100 const { ctx, w, h } = prepare(canvas);
101 const fg = color('--fg');
102 const left = 56;
103 const right = 10;
104 const top = 8;
105 const bottom = 30;
106 const pw = w - left - right;
107 const ph = h - top - bottom;
109 off.width = columns;
110 off.height = bins;
111 off.getContext('2d').putImageData(image, 0, 0);
112 ctx.imageSmoothingEnabled = true;
113 ctx.drawImage(off, left, top, pw, ph);
115 ctx.strokeStyle = fg;
116 ctx.fillStyle = fg;
117 ctx.lineWidth = 1;
118 ctx.strokeRect(left, top, pw, ph);
119 ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif';
121 if (!started) {
122 ctx.globalAlpha = 0.6;
123 ctx.textAlign = 'center';
124 ctx.textBaseline = 'middle';
125 ctx.fillText('Press Play to see the spectrum of the sound', left + pw / 2, top + ph / 2);
126 ctx.globalAlpha = 1;
127 }
129 // time before now, with now at the right edge
130 ctx.textAlign = 'center';
131 ctx.textBaseline = 'top';
132 for (let sec = 0; sec <= SPEC_SECONDS; sec++) {
133 const x = left + pw - (sec / SPEC_SECONDS) * pw;
134 ctx.beginPath();
135 ctx.moveTo(x, top + ph);
136 ctx.lineTo(x, top + ph + 4);
137 ctx.stroke();
138 ctx.fillText(sec === 0 ? 'now' : `−${sec} s`, x, top + ph + 7);
139 }
140 const fTop = (bins * rate) / SPEC_FFT;
141 ctx.textAlign = 'right';
142 ctx.textBaseline = 'middle';
143 for (let f = 0; f <= SPEC_FMAX; f += 500) {
144 const y = top + ph - (f / fTop) * ph;
145 ctx.beginPath();
146 ctx.moveTo(left - 4, y);
147 ctx.lineTo(left, y);
148 ctx.stroke();
149 ctx.fillText(`${f} Hz`, left - 7, y);
150 }
151 }
153 return { attach, detach, draw };
↑↓ move↵openescclose