Embed
The script finds its own origin, so nothing else is needed; the widget runs in a sandboxed frame and cannot touch your page. Set the controls and the two lines update; the preview beneath shows what your readers get.
<script src="https://learn.mimmsy.com/learn-widget.js"></script>
<learn-widget name="fft-live-analyzer"></learn-widget> It is CC-BY-4.0: keep the credit line the frame shows.
Preview
Fork
A fork is a copy whose manifest names its parent and the parent's version; lineage is kept forever, and the copy is yours to change. The library is its own repository: clone it, copy fft-live-analyzer/ to a new name (one DNS label), set forkedFrom to { "name": "fft-live-analyzer", "version": 1 }, change what you want, run npm run check, and open a pull request. Passing the check is the whole gate. Without a checkout, submit the same files to POST /api/widgets and it is served instantly as an unreviewed draft.
Source
The whole widget is these files; the repository has their history.
widget.json
{
"name": "fft-live-analyzer",
"title": "Live FFT analyzer",
"version": 1,
"claim": "A 2,048-point FFT computed every screen frame tracks a moving sweep, resolves a chord into its harmonics, and finds a tone buried in noise, each transform costing a fraction of a millisecond.",
"summary": "Press play to run a Hann-windowed 2,048-point FFT on the playhead every frame and draw the magnitudes in decibels, with the tallest bin and the per-frame FFT time read out. The sandbox has no microphone, so the sources are synthesized: a sweep over a 440 Hz drone, a chord of harmonics, white noise with a hidden 1 kHz tone, and a short song built from a few harmonics.",
"topics": [
"signals/fourier",
"audio/digital"
],
"aliases": [
"spectrum analyzer",
"real-time FFT",
"Hann window",
"chirp",
"spectrogram"
],
"params": {
"source": {
"type": "string",
"default": "sweep",
"enum": [
"sweep",
"chord",
"noise",
"song"
],
"label": "synthesized source"
}
},
"check": [
{
"q": "In a spectrum, a single tall spike above a flat floor suggests…",
"options": [
"two tones an octave apart",
"a steady tone plus broadband noise",
"a DC offset in the recording",
"clipping in the recording"
],
"answer": 1,
"why": "A tone concentrates its energy in one bin; noise spreads its energy across all of them, which is why the noise source’s hidden 1 kHz tone shows plainly in the spectrum."
},
{
"q": "The analyzer runs a 2,048-point FFT 60 times per second. Roughly how many twiddle multiplications is that per second?",
"options": [
"11,264",
"about 0.7 million",
"2,048",
"about 250 million"
],
"answer": 1,
"why": "(N/2)·log₂N = 11,264 multiplications per transform, times 60 frames ≈ 0.7 million per second; the direct DFT would need about 250 million for the same display."
}
],
"capabilities": [],
"height": 432,
"requires": [],
"forkedFrom": null,
"authors": []
}
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Live FFT analyzer</title>
<style>
:root {
color-scheme: light dark;
--bg: #f7f3ea;
--bg-card: #efe9da;
--border: #d8cfba;
--text: #211d14;
--text-dim: #6e6553;
--accent: #31597f;
--accent2: #b04e1b;
--hot: #a82433;
--ok: #3d6b4f;
--ink-rgb: 33, 29, 20;
--paper-rgb: 247, 243, 234;
--accent-rgb: 49, 89, 127;
--accent2-rgb: 176, 78, 27;
--hot-rgb: 168, 36, 51;
--ok-rgb: 61, 107, 79;
--serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif;
--mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161410;
--bg-card: #1e1b15;
--border: #383225;
--text: #e9e3d3;
--text-dim: #9c917c;
--accent: #8fb8e0;
--accent2: #dd9355;
--hot: #df7a88;
--ok: #82bd97;
--ink-rgb: 233, 227, 211;
--paper-rgb: 22, 20, 16;
--accent-rgb: 143, 184, 224;
--accent2-rgb: 221, 147, 85;
--hot-rgb: 223, 122, 136;
--ok-rgb: 130, 189, 151;
}
}
* { box-sizing: border-box; }
html, body { margin: 0; }
body { background: transparent; color: var(--text); font-family: var(--serif); font-size: 15px; line-height: 1.5; }
.widget { background: var(--bg-card); border: 1px solid var(--border); border-radius: 4px; padding: 22px; }
.control-row { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-bottom: 14px; }
.control-row label { font-size: 14px; color: var(--text-dim); white-space: nowrap; }
.control-row.sym { display: grid; grid-template-columns: 88px 1fr 1fr; gap: 12px 16px; align-items: center; }
.control-row.sym.single { grid-template-columns: 88px 1fr; }
.ctl { display: flex; align-items: center; gap: 10px; min-width: 0; }
.ctl input[type="range"] { flex: 1; min-width: 0; }
.ctl .val { flex: none; width: 64px; text-align: right; font-size: 13px; }
@media (max-width: 600px) {
.control-row.sym { grid-template-columns: 64px 1fr; }
.control-row.sym .ctl:nth-of-type(2) { grid-column: 2; }
}
input[type="range"] { flex: 1; min-width: 110px; accent-color: var(--accent); }
.toggle { display: inline-flex; align-items: baseline; gap: 7px; font-size: 13.5px; color: var(--text-dim); cursor: pointer; }
.toggle input { accent-color: var(--accent2); }
.control-row .toggle { white-space: normal; }
.mono { font-family: var(--mono); }
.dim { color: var(--text-dim); font-size: 12.5px; }
.chips { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; }
.chip, .btn {
font-family: var(--mono); font-size: 12.5px; color: var(--text); background: transparent;
border: 1px solid var(--border); border-radius: 3px; padding: 6px 13px; cursor: pointer;
transition: border-color 0.15s, color 0.15s;
}
.chip:hover, .btn:hover { border-color: var(--accent); color: var(--accent); }
.btn.primary { border-color: var(--accent); color: var(--accent); }
.btn.playing, .btn.playing:hover { border-color: var(--hot); color: var(--hot); }
.btn.off { border-color: var(--hot); color: var(--hot); opacity: 0.85; }
.btn:disabled { opacity: 0.35; cursor: default; }
.btn:disabled:hover { border-color: var(--border); color: var(--text); }
.chip.sel-chip { border-color: var(--accent); color: var(--accent); }
.readout-row { display: flex; gap: 28px; flex-wrap: wrap; margin: 14px 0 0; }
.readout { text-align: left; }
.readout.inline { margin-left: auto; text-align: right; }
.readout .big { display: block; font-size: 30px; font-weight: 600; color: var(--accent); line-height: 1.1; min-width: 5ch; }
.readout.accent .big { color: var(--accent2); }
.readout .big.hot { color: var(--hot); }
.readout small { color: var(--text-dim); font-size: 12.5px; }
@media (max-width: 560px) { .readout .big { font-size: 25px; } }
.plot { display: block; width: 100%; height: 220px; margin-top: 8px; }
.plot.tall { height: 280px; }
.plot.duo { height: 320px; }
.plot.phasor { height: 400px; }
.plot.spec { height: 230px; }
.mono, .ctl .val, .readout .big, .readout small { font-variant-numeric: tabular-nums; }
</style>
</head>
<body>
<div class="widget">
<div class="chips">
<button class="btn primary" id="ana-play">▶ play · live FFT analyzer</button>
<button class="chip" data-source="sweep">sweep + 440 Hz</button>
<button class="chip" data-source="chord">chord of harmonics</button>
<button class="chip" data-source="noise">noise + hidden tone</button>
<button class="chip" data-source="song">a short song</button>
</div>
<canvas id="spec-canvas" class="plot spec"></canvas>
<div class="readout-row">
<div class="readout">
<span class="big mono" id="ana-peak">—</span>
<small>tallest bin · Hz</small>
</div>
<div class="readout accent">
<span class="big mono" id="ana-ms">—</span>
<small>2,048-point FFT · ms per frame</small>
</div>
<div class="readout">
<span class="big mono" id="ana-source">sweep</span>
<small>source · synthesized, no microphone</small>
</div>
</div>
</div>
<script src="/w/_sdk/host.js?v=1"></script>
<script src="/w/_lib/dsp.js?v=1"></script>
<script src="widget.js?v=1"></script>
</body>
</html>
widget.js
/* Live FFT analyzer: a 2,048-point Hann-windowed FFT of the playhead each frame, over synthesized sources (the sandbox has no microphone). */
(() => {
'use strict';
const $ = (id) => document.getElementById(id);
const { T, clamp, setupCanvas, hline, vGradient, fft, signal } = DSP;
const N = 2048;
const T_SEC = 4;
const SOURCES = ['sweep', 'chord', 'noise', 'song'];
const hann = Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (N - 1)));
const re = new Float64Array(N);
const im = new Float64Array(N);
let source = 'sweep';
let cache = {};
let active = false;
let t0 = 0;
let buf = null;
let playing = false;
function fade(t, total) { return Math.min(t / 0.03, (total - t) / 0.06, 1); }
function synth(kind, sr) {
const total = Math.floor(T_SEC * sr);
const data = new Float32Array(total);
if (kind === 'sweep') {
let phase = 0;
for (let i = 0; i < total; i++) {
const t = i / sr;
const f = 120 * Math.pow(4200 / 120, t / T_SEC);
phase += (2 * Math.PI * f) / sr;
data[i] = fade(t, T_SEC) * (0.42 * Math.sin(phase) + 0.13 * Math.sin(2 * Math.PI * 440 * t));
}
} else if (kind === 'chord') {
const notes = [220, 277.18, 329.63, 440];
for (let i = 0; i < total; i++) {
const t = i / sr;
let v = 0;
for (const f of notes) for (let m = 1; m <= 3; m++) v += (0.12 / m) * Math.sin(2 * Math.PI * f * m * t);
data[i] = fade(t, T_SEC) * v;
}
} else if (kind === 'noise') {
for (let i = 0; i < total; i++) {
const t = i / sr;
data[i] = fade(t, T_SEC) * (0.22 * (Math.random() * 2 - 1) + 0.05 * Math.sin(2 * Math.PI * 1000 * t));
}
} else {
const notes = [262, 330, 392, 523, 440, 392, 330, 262];
const noteDur = T_SEC / notes.length;
notes.forEach((f, ni) => {
const start = Math.floor(ni * noteDur * sr);
const len = Math.floor(noteDur * sr);
for (let i = 0; i < len && start + i < total; i++) {
const t = i / sr;
const env = Math.min(t / 0.01, 1) * Math.exp(-2.4 * t);
let v = 0;
for (let m = 1; m <= 4; m++) v += (0.3 / m) * Math.sin(2 * Math.PI * f * m * t);
data[start + i] = env * v;
}
});
}
return data;
}
function getBuffer() {
const ctx = DSP.audioCtx();
const key = source + '@' + ctx.sampleRate;
if (!cache[key]) cache[key] = synth(source, ctx.sampleRate);
return cache[key];
}
function drawIdle() {
const { ctx, w, h } = setupCanvas($('spec-canvas'));
ctx.clearRect(0, 0, w, h);
ctx.strokeStyle = T.GRID;
ctx.strokeRect(0.5, 0.5, w - 1, h - 1);
ctx.font = DSP.font(12);
DSP.label(ctx, 'press play to show the live spectrum of the ' + source + ' source', w / 2, h / 2, T.DIM, 'center');
$('ana-peak').textContent = '—';
$('ana-ms').textContent = '—';
}
function frame() {
if (!active) return;
const actx = DSP.audioCtx();
const sr = actx.sampleRate;
const elapsed = actx.currentTime - t0;
const pos = Math.floor((elapsed % T_SEC) * sr);
const off = clamp(pos, 0, buf.length - N - 1);
const tf0 = performance.now();
for (let i = 0; i < N; i++) { re[i] = buf[off + i] * hann[i]; im[i] = 0; }
fft(re, im, false);
const fftMs = performance.now() - tf0;
const { ctx, w, h } = setupCanvas($('spec-canvas'));
const m = { l: 14, r: 14, t: 12, b: 24 };
const pw = w - m.l - m.r;
const ph = h - m.t - m.b;
const maxHz = 5000;
const binMax = Math.min(N / 2, Math.floor((maxHz / sr) * N));
const BARS = 72;
ctx.clearRect(0, 0, w, h);
hline(ctx, m.l, w - m.r, h - m.b, T.GRID);
let peakK = 1, peakMag = 0;
for (let k = 1; k < binMax; k++) {
const mag = Math.hypot(re[k], im[k]);
if (mag > peakMag) { peakMag = mag; peakK = k; }
}
for (let b = 0; b < BARS; b++) {
const k0 = Math.floor((b / BARS) * binMax) + 1;
const k1 = Math.max(k0 + 1, Math.floor(((b + 1) / BARS) * binMax));
let mx = 0;
for (let k = k0; k < k1; k++) mx = Math.max(mx, Math.hypot(re[k], im[k]));
const db = 20 * Math.log10(mx / (N / 4) + 1e-7);
const v = clamp((db + 64) / 64, 0, 1);
const bh = v * ph;
const slot = pw / BARS;
ctx.fillStyle = vGradient(ctx, h - m.b - bh, h - m.b);
ctx.fillRect(m.l + b * slot + slot * 0.12, h - m.b - Math.max(bh, 1), slot * 0.76, Math.max(bh, 1));
}
ctx.font = DSP.font(10);
for (let khz = 0; khz <= 5; khz++) {
const x = m.l + ((khz * 1000) / maxHz) * pw;
DSP.label(ctx, khz + ' kHz', x, h - 8, T.DIM, khz === 0 ? 'left' : 'center');
}
const peakHz = (peakK * sr) / N;
const px = m.l + (peakHz / maxHz) * pw;
DSP.label(ctx, '▼ ' + Math.round(peakHz) + ' Hz', clamp(px, m.l + 30, w - m.r - 30), m.t, T.ACCENT2, 'center');
$('ana-peak').textContent = Math.round(peakHz);
$('ana-ms').textContent = fftMs.toFixed(2);
requestAnimationFrame(frame);
}
function selectChip() {
document.querySelectorAll('.chip[data-source]').forEach((c) => c.classList.toggle('sel-chip', c.dataset.source === source));
$('ana-source').textContent = source;
}
let handle = null;
function startSource() {
const actx = DSP.audioCtx();
const data = getBuffer();
handle = DSP.bufferSource(actx, data, { gain: 0.5, loop: true });
buf = data;
t0 = actx.currentTime;
active = true;
requestAnimationFrame(frame);
}
DSP.playButton($('ana-play'), () => {
startSource();
playing = true;
signal('interaction', { play: source });
return () => {
playing = false;
active = false;
if (handle) handle.stop();
handle = null;
drawIdle();
};
});
document.querySelectorAll('.chip[data-source]').forEach((chip) => {
chip.addEventListener('click', () => {
source = chip.dataset.source;
selectChip();
signal('interaction', { source });
if (playing) {
active = false;
if (handle) handle.stop();
startSource();
} else {
drawIdle();
}
});
});
function applyParams(p) {
if (SOURCES.includes(p.source) && p.source !== source) {
source = p.source;
selectChip();
if (playing) { active = false; if (handle) handle.stop(); startSource(); }
else drawIdle();
}
}
selectChip();
drawIdle();
DSP.onResize(() => { if (!active) drawIdle(); });
DSP.connect({ render: () => { if (!active) drawIdle(); }, params: applyParams });
})();