{"spec_id":"spectrogram-mel","library":"muix","language":"javascript","code":"// anyplot.ai\n// spectrogram-mel: Mel-Spectrogram for Audio Analysis\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst N_MELS = 64; // number of mel filter banks\nconst N_FFT = 1024; // STFT frame length in samples (Hann window)\nconst HOP = 400; // samples between frame starts\nconst DYNAMIC_RANGE_DB = 70; // colour scale spans the peak down to this many dB below it; quieter cells clamp to the low end\nconst TICK_EVERY_BANDS = 8; // frequency ticks at every eighth mel band edge\nconst COLORBAR_TICK_TARGET = 8;\nconst POWER_LABEL = \"Power (dB re peak)\";\nconst FREQUENCY_LABEL = \"Frequency (Hz, mel-scaled)\";\n\n// Columns: set these to your data's column names\nconst TIME = \"Time (s)\"; // role: extra\nconst AMPLITUDE = \"Amplitude\"; // role: audio_signal\n\n// Data: replace this block with your own records, one object per row\n// A sung C-major arpeggio (C4, E4, G4, C5) with three decaying harmonics, 5 Hz vibrato\n// and a breathy onset, sampled at 16 kHz for 2.4 s\nconst data = (() => {\n  const sampleRate = 16000;\n  const duration = 2.4;\n  const notes = [261.63, 329.63, 392.0, 523.25];\n  const harmonicAmps = [1, 0.5, 0.22];\n  const noteDuration = duration / notes.length;\n  let s = 42 >>> 0;\n  const rand = () => {\n    s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n    return s / 0x100000000;\n  };\n  return Array.from({ length: Math.round(sampleRate * duration) }, (_, i) => {\n    const time = i / sampleRate;\n    const noteIndex = Math.min(notes.length - 1, Math.floor(time / noteDuration));\n    const localT = time - noteIndex * noteDuration;\n    const envelope = Math.sin(Math.PI * Math.min(1, localT / noteDuration));\n    // Vibrato as a frequency modulation of ±0.6 % at 5 Hz, integrated into the phase\n    const warpedTime = time + (0.006 * (1 - Math.cos(2 * Math.PI * 5 * time))) / (2 * Math.PI * 5);\n    const tone = harmonicAmps.reduce(\n      (acc, amp, h) => acc + amp * Math.sin(2 * Math.PI * notes[noteIndex] * (h + 1) * warpedTime),\n      0,\n    );\n    const breathyOnset = Math.exp(-time / 0.03) * 0.16 * (2 * rand() - 1);\n    const noiseFloor = 0.006 * (2 * rand() - 1);\n    return { [TIME]: time, [AMPLITUDE]: 0.6 * envelope * tone + breathyOnset + noiseFloor };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => a[TIME] - b[TIME]);\nconst signal = rows.map((d) => d[AMPLITUDE]);\nconst tStart = rows[0][TIME];\nconst sampleRate = (rows.length - 1) / (rows[rows.length - 1][TIME] - tStart);\nconst nFreq = N_FFT / 2 + 1;\nconst frameCount = Math.floor((signal.length - N_FFT) / HOP) + 1;\n\n// Mel filterbank (HTK mel formula) with Slaney area normalisation, so the wider\n// high-frequency filters do not sum more broadband noise than the narrow low ones\nconst melMax = 2595 * Math.log10(1 + sampleRate / 2 / 700);\nconst melStep = melMax / (N_MELS + 1);\nconst hzEdges = Array.from({ length: N_MELS + 2 }, (_, i) => 700 * (10 ** ((i * melStep) / 2595) - 1));\nconst binEdges = hzEdges.map((hz) => Math.floor(((N_FFT + 1) * hz) / sampleRate));\nconst melFilters = Array.from({ length: N_MELS }, (_, i) => {\n  const [lo, mid, hi] = [binEdges[i], binEdges[i + 1], binEdges[i + 2]];\n  const norm = 2 / (hzEdges[i + 2] - hzEdges[i]);\n  return Array.from({ length: nFreq }, (_, k) =>\n    k >= lo && k < mid\n      ? ((k - lo) / Math.max(1, mid - lo)) * norm\n      : k >= mid && k < hi\n        ? ((hi - k) / Math.max(1, hi - mid)) * norm\n        : 0,\n  );\n});\n\n// STFT power per frame, then mel power, then dB relative to the peak\nconst hann = Array.from({ length: N_FFT }, (_, n) => 0.5 - 0.5 * Math.cos((2 * Math.PI * n) / (N_FFT - 1)));\nconst cosTable = Array.from({ length: N_FFT }, (_, i) => Math.cos((2 * Math.PI * i) / N_FFT));\nconst sinTable = Array.from({ length: N_FFT }, (_, i) => Math.sin((2 * Math.PI * i) / N_FFT));\nconst melPower = Array.from({ length: frameCount }, (_, f) => {\n  const frame = hann.map((w, n) => w * signal[f * HOP + n]);\n  const spectrum = Array.from({ length: nFreq }, (_, k) => {\n    let re = 0;\n    let im = 0;\n    for (let n = 0; n < N_FFT; n += 1) {\n      const idx = (k * n) % N_FFT;\n      re += frame[n] * cosTable[idx];\n      im -= frame[n] * sinTable[idx];\n    }\n    return (re * re + im * im) / N_FFT;\n  });\n  return melFilters.map((filter) => filter.reduce((acc, w, k) => acc + w * spectrum[k], 0));\n});\nconst peakPower = Math.max(...melPower.map((col) => Math.max(...col)));\n\n// Cells: one per frame and mel band, centred on the frame's centre time and the band's centre mel\nconst frameStep = HOP / sampleRate;\nconst seqRgb = t.seq.map((hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)));\nconst cells = melPower.flatMap((col, f) =>\n  col.map((p, m) => {\n    const db = Math.max(-DYNAMIC_RANGE_DB, 10 * Math.log10(Math.max(p, 1e-12) / peakPower));\n    const v = (db + DYNAMIC_RANGE_DB) / DYNAMIC_RANGE_DB;\n    const centre = tStart + (f * HOP + N_FFT / 2) / sampleRate;\n    return {\n      key: `${f}-${m}`,\n      t0: centre - frameStep / 2,\n      t1: centre + frameStep / 2,\n      mel0: (m + 0.5) * melStep,\n      mel1: (m + 1.5) * melStep,\n      fill: `rgb(${seqRgb[0].map((c, j) => Math.round(c + (seqRgb[1][j] - c) * v)).join(\",\")})`,\n    };\n  }),\n);\nconst xMin = cells[0].t0;\nconst xMax = cells[cells.length - 1].t1;\nconst yMin = 0.5 * melStep;\nconst yMax = (N_MELS + 0.5) * melStep;\nconst melTicks = Array.from(\n  { length: Math.floor(N_MELS / TICK_EVERY_BANDS) + 1 },\n  (_, i) => (i * TICK_EVERY_BANDS + 0.5) * melStep,\n);\n\nconst rawStep = DYNAMIC_RANGE_DB / COLORBAR_TICK_TARGET;\nconst stepMagnitude = 10 ** Math.floor(Math.log10(rawStep));\nconst dbStep = [1, 2, 5, 10].map((mul) => mul * stepMagnitude).find((s) => s >= rawStep);\nconst dbTicks = Array.from({ length: Math.floor(DYNAMIC_RANGE_DB / dbStep) + 1 }, (_, i) => -i * dbStep);\n\nconst TITLE = \"spectrogram-mel · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${rows.length.toLocaleString(\"en-US\")} samples at ${Math.round(sampleRate).toLocaleString(\n  \"en-US\",\n)} Hz · ${N_MELS} mel bands up to ${Math.round(sampleRate / 2).toLocaleString(\"en-US\")} Hz · FFT ${N_FFT}, hop ${HOP} (${(\n  frameStep * 1000\n).toFixed(0)} ms per frame)`;\nconst HEADER_H = 92;\nconst BAR_W = 22;\nconst BAR_GAP = 24;\n\nfunction MelCells() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g shapeRendering=\"crispEdges\">\n      {cells.map((c) => (\n        <rect\n          key={c.key}\n          x={xScale(c.t0)}\n          y={yScale(c.mel1)}\n          width={xScale(c.t1) - xScale(c.t0) + 0.6}\n          height={yScale(c.mel0) - yScale(c.mel1) + 0.6}\n          fill={c.fill}\n        />\n      ))}\n    </g>\n  );\n}\n\nfunction Colorbar() {\n  const { left, top, width, height } = useDrawingArea();\n  const x = left + width + BAR_GAP;\n  return (\n    <g>\n      <defs>\n        <linearGradient id=\"melColorbar\" x1=\"0\" y1=\"1\" x2=\"0\" y2=\"0\">\n          <stop offset=\"0%\" stopColor={t.seq[0]} />\n          <stop offset=\"100%\" stopColor={t.seq[1]} />\n        </linearGradient>\n      </defs>\n      <rect x={x} y={top} width={BAR_W} height={height} fill=\"url(#melColorbar)\" />\n      {dbTicks.map((db) => (\n        <g key={db}>\n          <line\n            x1={x + BAR_W}\n            x2={x + BAR_W + 6}\n            y1={top + (-db / DYNAMIC_RANGE_DB) * height}\n            y2={top + (-db / DYNAMIC_RANGE_DB) * height}\n            stroke={t.inkSoft}\n          />\n          <text\n            x={x + BAR_W + 10}\n            y={top + (-db / DYNAMIC_RANGE_DB) * height}\n            dominantBaseline=\"middle\"\n            fontSize={18}\n            fill={t.inkSoft}\n          >\n            {db === 0 ? \"0\" : `−${-db}`}\n          </text>\n        </g>\n      ))}\n      <text\n        x={x + BAR_W + 74}\n        y={top + height / 2}\n        textAnchor=\"middle\"\n        fontSize={20}\n        fill={t.ink}\n        transform={`rotate(90, ${x + BAR_W + 74}, ${top + height / 2})`}\n      >\n        {POWER_LABEL}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: HEADER_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          justifyContent: \"center\",\n          alignItems: \"center\",\n          gap: 8,\n        }}\n      >\n        <div style={{ fontSize: 26, fontWeight: 600, color: t.ink }}>{TITLE}</div>\n        <div style={{ fontSize: 18, color: t.inkSoft }}>{SUBTITLE}</div>\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - HEADER_H}\n        margin={{ top: 12, right: 156, bottom: 12, left: 24 }}\n        skipAnimation\n        series={[]}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            min: xMin,\n            max: xMax,\n            label: TIME,\n            height: 70,\n            tickNumber: 12,\n            valueFormatter: (v) => v.toFixed(1),\n            tickLabelStyle: { fontSize: 18, fill: t.inkSoft },\n            labelStyle: { fontSize: 20, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: yMin,\n            max: yMax,\n            tickInterval: melTicks,\n            valueFormatter: (mel) => Math.round(700 * (10 ** (mel / 2595) - 1)).toLocaleString(\"en-US\"),\n            label: FREQUENCY_LABEL,\n            width: 108,\n            tickLabelStyle: { fontSize: 18, fill: t.inkSoft },\n            labelStyle: { fontSize: 20, fill: t.ink },\n          },\n        ]}\n      >\n        <MelCells />\n        <Colorbar />\n        <ChartsXAxis />\n        <ChartsYAxis />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}