Skip to content

Draw a Mel Spectrogram in the Browser ​

To show a mel spectrogram of a file a visitor picks, decode its bytes with Audio.fromMemoryWithBrowserFallback, call melSpectrogram on the samples, take the power converted to dB, and paint it onto a <canvas>. All of it runs in the page through WebAssembly; the file never leaves the visitor's machine. The code below is the whole job.

html
<input type="file" id="pick" accept="audio/*" />
<canvas id="mel" style="width: 100%; height: 256px"></canvas>
js
import { Audio, init, melSpectrogram } from '@libraz/libsonare';

await init();

// dB matrix -> RGBA pixels. Row 0 of the matrix is the lowest band, so flip it
// to put low frequencies at the bottom. The brightest cell is the peak; the
// range below it is the matrix's own 80 dB floor.
function toPixels({ data, rows, cols }, rangeDb = 80) {
  let peak = -Infinity;
  for (const v of data) peak = Math.max(peak, v);
  const pixels = new Uint8ClampedArray(rows * cols * 4);
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const t = Math.min(1, Math.max(0, (data[r * cols + c] - (peak - rangeDb)) / rangeDb));
      const o = ((rows - 1 - r) * cols + c) * 4;
      pixels[o] = 255 * Math.min(1, 2 * t);
      pixels[o + 1] = 255 * Math.max(0, 2 * t - 1);
      pixels[o + 2] = 255 * t * (1 - t) * 2;
      pixels[o + 3] = 255;
    }
  }
  return pixels;
}

export async function drawMel(file, canvas) {
  const bytes = new Uint8Array(await file.arrayBuffer());
  const audio = await Audio.fromMemoryWithBrowserFallback(bytes);
  try {
    const mel = melSpectrogram({ samples: audio.data, sampleRate: audio.sampleRate });
    canvas.width = mel.db.cols;
    canvas.height = mel.db.rows;
    const image = new ImageData(toPixels(mel.db), mel.db.cols, mel.db.rows);
    canvas.getContext('2d').putImageData(image, 0, 0);
  } finally {
    audio.destroy();
  }
}

document.getElementById('pick').addEventListener('change', (e) => {
  drawMel(e.target.files[0], document.getElementById('mel'));
});

WAV and MP3 are decoded by the engine itself; other formats the browser can play, such as AAC, OGG and FLAC, go through the browser's own decoder, and a stereo file is folded to mono before analysis. destroy() releases the decoded samples, which matters when a visitor drops one file after another.

The canvas is one pixel per cell, so its backing size is the matrix size and CSS stretches it to fit the page. A two-second clip at 22.05 kHz gives 128 bands by 87 frames with the defaults.

The demo draws the same kind of matrix for a vowel-like tone, so the harmonic and formant bands can be compared with the linear-frequency spectrogram.

MEL · SPECTRALIDLE
Mel spectrogram — frequency the way we hear it

The mel spectrogram combines STFT power into perceptually spaced frequency bands: narrower at low frequencies and wider at high frequencies. Compare the harmonic and formant bands with the linear-frequency STFT. The mel scale approximates aspects of frequency perception; it is not a direct measurement of the ear.

Mel bands and dB, in a minute

A spectrogram splits the sound into frequencies over time. Mel bands group those frequencies the way hearing does: narrow bands at the bottom, where the ear tells pitches apart finely, and wide bands at the top, so 128 rows cover the whole range without most of them sitting in the treble. dB is a log scale for power. Each +10 dB is ten times the power, which is what lets a quiet detail and a loud peak share one picture. melSpectrogram returns both forms: power is the linear values and db is the same matrix in dB, kept within 80 dB of the loudest value. See Mel, MFCC and timbre.

What you need

  • Install: npm install @libraz/libsonare.
  • An audio file: anything the browser can decode.
  • To reproduce the numbers on this page: a 1 kHz sine at 22.05 kHz puts its energy in band 38 of 128, whose centre is 1006 Hz.

What the result holds ​

  • db and power are { data, rows, cols }, row-major: the value for band r at frame c is data[r * cols + c]. Rows are mel bands from fminHz up to fmaxHz, columns are frames.
  • Defaults are nFft: 2048, hopLength: 512, nMels: 128, fminHz: 0, fmaxHz the Nyquist, and the Slaney mel scale. Pass htk: true for the HTK formula.
  • To label the rows with frequencies, ask the engine for the scale: melFrequencies({ nMels: 130, fmaxHz: audio.sampleRate / 2 }).subarray(1, -1) is the 128 band centres in Hz, lowest first. Band r rises from point r of those 130 points, peaks at point r + 1 and falls to point r + 2, which is how the 1006 Hz centre of band 38 above is read. Pass fmaxHz explicitly: melFrequencies defaults it to 11025 Hz, not to a Nyquist it has no sample rate for. Give it the same fminHz and htk as the spectrogram, and melFilterbank returns the filters themselves.
  • For another floor or reference, convert power yourself: powerToDb({ values: mel.power.data, topDb: 60 }) returns a Float32Array in the same layout. Its conversion matches librosa's power_to_db on the reference values the library's own tests compare against.

Long files: do it in a Web Worker ​

melSpectrogram is synchronous, so a long song freezes the page while it runs. Decode on the main thread, which has the browser's decoder, then hand the samples to a worker and draw what comes back.

js
// mel.worker.js
import { init, melSpectrogram } from '@libraz/libsonare';

const ready = init();

self.onmessage = async ({ data: { samples, sampleRate, hopLength } }) => {
  await ready;
  const { db } = melSpectrogram({ samples, sampleRate, hopLength });
  self.postMessage(db, [db.data.buffer]);
};
js
// main thread, inside drawMel in place of the melSpectrogram call
const worker = new Worker(new URL('./mel.worker.js', import.meta.url), { type: 'module' });
const samples = audio.data.slice();
const db = await new Promise((resolve) => {
  worker.onmessage = (e) => resolve(e.data);
  worker.postMessage({ samples, sampleRate: audio.sampleRate, hopLength: 2048 }, [samples.buffer]);
});
worker.terminate();

audio.data is shared with the Audio object, so copy it with slice() before transferring. A larger hopLength keeps the canvas narrow: at 512, a five-minute song at 44.1 kHz is about 25,800 columns, close to the 32,767-pixel width limit many browsers put on a canvas, and at 2048 it is about 6,500. Web Worker Usage covers the bundled worker client for the calls it supports.