Using WaveformAPI with WaveSurfer.js
WaveSurfer.js is a popular library for audio visualization, but decoding audio in the browser can be slow and memory-intensive, especially for large files. WaveformAPI solves this by providing pre-calculated peaks.
The Problem
By default, WaveSurfer.js downloads the entire audio file and uses the Web Audio API to decode it and calculate peaks. This process:
- Consumes significant CPU and memory on the client device.
- Causes a delay before the waveform is visible.
- Can crash the browser tab with large files or on mobile devices.
The Solution
WaveformAPI generates the peak data on our servers in milliseconds. You simply fetch this JSON data and pass it to WaveSurfer.js. The waveform renders instantly, without downloading the full audio file first.
Implementation
Step 1: Generate Peaks
// POST https://api.waveformapi.com/v1/generate
{
"url": "https://example.com/audio.mp3"
}Step 2: Initialize WaveSurfer
import WaveSurfer from 'wavesurfer.js';
// 1. Fetch the peaks from WaveformAPI
const response = await fetch('https://api.waveformapi.com/v1/generate', {
method: 'POST',
headers: { 'Authorization': 'Bearer YOUR_KEY' },
body: JSON.stringify({ url: '...' })
});
const { data } = await response.json();
// 2. Normalize peaks (WaveSurfer expects -1 to 1 or 0 to 1, API returns 8-bit or 16-bit integers)
// WaveformAPI returns 8-bit (-128 to 127) or 16-bit.
// Simple normalization example for 8-bit:
const peaks = data.map(p => p / 128);
// 3. Initialize with peaks
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple',
backend: 'MediaElement', // Recommended for large files
peaks: [peaks] // Pass the peaks here!
});
// 4. Load audio (rendering happens instantly because peaks are provided)
wavesurfer.load('https://example.com/audio.mp3');Benefits
- Instant Rendering: No waiting for decoding.
- Low Memory Usage: Browser doesn't need to decode the whole file.
- Mobile Friendly: Works smoothly even on low-end devices.