Documentation

Load a track or open the microphone, read bass, mid and high, and move anything you build.

01Quick start

audio-bands is a browser audio analysis library. It turns a track or a microphone into numbers you can use in any renderer. React is optional; Web Audio runs in the browser.

Terminal
npm install @juandinella/audio-bands

Put an audio file at /track.mp3, add a button and an output element. This complete example loads the file first, then starts playback from a click.

main.js
import { AudioBands } from '@juandinella/audio-bands';

// HTML: <button id="play" disabled>Play</button>
//       <pre id="output"></pre>
const button = document.querySelector('#play');
const output = document.querySelector('#output');
const audio = new AudioBands();
let disposed = false;
let raf = 0;

async function toggle() {
  try {
    await audio.togglePlayPause();
    button.textContent = audio.getState().isPlaying ? 'Pause' : 'Play';
  } catch (error) {
    output.textContent = error.message;
  }
}
button.addEventListener('click', toggle);

audio.load('/track.mp3').then(() => {
  if (!disposed) button.disabled = false;
}).catch(error => { output.textContent = error.message; });

function loop() {
  const { bands } = audio.snapshot();
  output.textContent = JSON.stringify(bands, null, 2);
  raf = requestAnimationFrame(loop);
}
raf = requestAnimationFrame(loop);

// Call when removing this UI.
export function cleanup() {
  disposed = true;
  cancelAnimationFrame(raf);
  button.removeEventListener('click', toggle);
  audio.destroy();
}

The animation loop reads current values. In a canvas or 3D scene, update the renderer directly rather than putting every frame in React state, and cancel the loop when the view is removed.

02React

Import useAudioBands from @juandinella/audio-bands/react. It owns the audio instance and releases it on unmount. The root and /core exports do not require React.

The hook exposes loadTrack instead of load, and toggleMic instead of separate microphone methods. It returns isPlaying, hasTrack, micActive and separate loadError, playbackError and micError. Your effect still owns its animation loop.

Changing the music, mic, bandRanges or customBands options recreates the instance and stops playback. To adjust analysis while audio plays, keep options stable and use the live settings.

03Reading audio

bass, mid and high are normalized regions of the analyser spectrum, each from 0 to 1. They are control signals for visuals, not calibrated loudness. overall is bass × 0.5 + mid × 0.3 + high × 0.2.

Inside your animation loop
const frame = audio.snapshot();
const { bass, mid, high, overall } = frame.bands;
const fft = frame.fft;           // frequency bytes, 0–255
const waveform = frame.waveform; // time-domain bytes, 0–255

Use getBands() for one control signal. Use snapshot() when you need several views of the same frame. FFT and waveform buffers are reused: copy with frame.fft?.slice() to keep a frame. Before a source starts they are null.

04Microphone

Call enableMic() from a click. The browser asks for permission; HTTPS or localhost is required. The microphone is never connected to the speakers.

mic.js
async function startMic() {
  try {
    await audio.enableMic();
  } catch (error) {
    // Show the error beside your microphone button.
    output.textContent = error.message;
  }
}

// In your animation loop:
const frame = audio.snapshot('mic');

// When the user stops:
audio.disableMic();

Music and microphone have separate analysers and can run at once. Read each explicitly with snapshot('music') and snapshot('mic'); the library does not mix them.

05Live settings

New in 0.7 Band regions, fftSize and smoothing can change on a running instance without stopping the audio. Invalid input throws invalid_config and keeps the previous settings.

Adjusting while it plays
// Move the bass/mid edge to ~120 Hz without stopping playback.
const nyquist = audio.getSampleRate() / 2;
audio.setBandRanges({
  bass: { from: 0, to: 120 / nyquist },
  mid: { from: 120 / nyquist, to: 4000 / nyquist },
});

// Slower, finer analysis for the music source.
audio.setAnalyserConfig('music', { fftSize: 2048, smoothingTimeConstant: 0.95 });

Ranges are shares of the spectrum from 0 Hz to half the sample rate, in equal-width bins. A share times getSampleRate() / 2 gives Hz; each edge snaps to a whole bin, so more bins give finer edges. A new fftSize replaces the buffers snapshot() returns.

New in 0.8 The default ranges are set in Hz: bass 0–250, mid 250–4000 and high 4000–16000, at whatever sample rate the device runs. The defaults also moved to fftSize 1024 and, for music, smoothing 0.7, so the bands follow the music more closely. Ranges you pass are still shares of the spectrum.

06API reference

Create an instance with new AudioBands(options?). Reading methods take 'music' (the default) or 'mic'. Async methods reject with an AudioBandsError; catch them even when you use callbacks.

MethodReturnsWhat it does
Playback
load(url)Promise<void>Load a CORS-enabled track. Resolves when ready; does not play.
play() · pause()Promise<void> · voidStart or pause the current track. Call play() from a click.
togglePlayPause()Promise<void>Toggle playback. Catch the returned promise.
setLoop(loop)voidLoop the current and future tracks.
seek(seconds)voidMove the playback position.
getDuration() · getCurrentTime()number | nullRead seconds, or null when unavailable.
Microphone
enableMic() · disableMic()Promise<void> · voidRequest microphone access; stop every microphone track.
Reading
snapshot(source?){ bands, customBands, fft, waveform }One coherent frame: one frequency read and one time-domain read.
getBands(source?){ bass, mid, high, overall }Each from 0 to 1.
getCustomBands(source?)Record<string, number>Your named spectrum regions, each from 0 to 1.
getFftData(source?)Uint8Array | nullfftSize / 2 frequency bins, 0–255. Reused buffer.
getWaveform(source?)Uint8Array | nullfftSize time-domain samples, 0–255. Reused buffer.
Live settings
setBandRanges(ranges)0.7voidChange bass/mid/high regions while playing. Omitted bands keep theirs.
getBandRanges()0.7{ bass, mid, high }Copies of the current regions.
setAnalyserConfig(source, config)0.7voidChange fftSize and smoothing for music or mic while playing.
getAnalyserConfig(source?)0.7{ fftSize, smoothingTimeConstant }The current analyser settings.
getSampleRate()0.7number | nullThe AudioContext rate; null before the first load or mic.
Lifecycle
getState()AudioBandsStateisPlaying, hasTrack, micActive and separate load, playback and mic errors.
destroy()voidRelease the audio context, the track and the microphone stream.

07Configuration

Constructor options
const audio = new AudioBands({
  music: { fftSize: 2048, smoothingTimeConstant: 0.6 },
  mic: { fftSize: 512, smoothingTimeConstant: 0.8 },
  customBands: {
    presence: { from: 0.25, to: 0.5 },
    air: { from: 0.5, to: 1 },
  },
  onLoadError: (error) => console.error(error),
  onMicError: (error) => console.error(error),
});
OptionTypeDefaultRange
music.fftSizenumber1024power of two, 32–32768
music.smoothingTimeConstantnumber0.70–1
mic.fftSizenumber1024power of two, 32–32768
mic.smoothingTimeConstantnumber0.80–1
bandRanges.bass{ from, to }0 – 250 Hz0 ≤ from < to ≤ 1
bandRanges.mid{ from, to }250 – 4000 Hz0 ≤ from < to ≤ 1
bandRanges.high{ from, to }4000 – 16000 Hz0 ≤ from < to ≤ 1
customBandsRecord<string, { from, to }>{}0 ≤ from < to ≤ 1
on…callbacks—Error, LoadError, PlaybackError, MicError, StateChange, Play, Pause, MicStart, MicStop

08Troubleshooting

Why does playback fail?

Browsers require a user gesture. Load the track first, then call play() directly from a click or tap. Awaiting a network load before playing can lose user activation.

Why is my remote track silent?

The audio server must allow cross-origin access with CORS headers. A URL that plays in a browser tab may still be unavailable to Web Audio. Test with a same-origin file first.

Why is the microphone unavailable?

Use HTTPS or localhost, grant permission, and check that no other application holds the device. Show microphone errors apart from track errors.

Why are my saved FFT frames changing?

The typed-array buffers are reused on every read, and replaced when fftSize changes. Copy with .slice() before storing a frame.

Why is high always low?

Ranges are shares of the spectrum up to half the sample rate. Compressed audio is nearly empty above ~16 kHz, which pulls the average of a wide high band down. Narrow it with setBandRanges() or add a custom band.

Can this run on the server?

Analysis needs the browser’s Web Audio API. Render the page on the server, but load tracks and start audio from effects or event handlers.