How Do You Initialize Wavesurfer.js in a Web App?

To initialize Wavesurfer.js in a web application, you need to include the library via a CDN or npm package, prepare a container HTML element, and instantiate the Wavesurfer class with your target container and audio file URL. Wavesurfer.js then automatically fetches, decodes, and renders the interactive audio waveform inside your designated DOM element.

Prerequisites and Installation

Before initializing Wavesurfer.js, ensure you have a container element in your HTML where the waveform will render. You can install the library using npm or load it directly via a CDN link in your HTML file.

npm install wavesurfer.js

Alternatively, you can load it directly in the browser using a script tag:

<script src="https://unpkg.com/wavesurfer.js@7"></script>

Creating the Container Element

Wavesurfer needs a DOM element (usually a <div>) to mount the canvas-rendered waveform. Create a container element with a unique ID in your HTML structure.

<div id="waveform"></div>
<button id="playBtn">Play / Pause</button>

Initializing Wavesurfer.js in JavaScript

To create the waveform, import Wavesurfer if using a module bundler, then call WaveSurfer.create() passing an options object. The container and url parameters are required.

import WaveSurfer from 'wavesurfer.js';

const wavesurfer = WaveSurfer.create({
  container: '#waveform',
  waveColor: '#4F46E5',
  progressColor: '#818CF8',
  url: '/path/to/audio-file.mp3',
  height: 128,
  barWidth: 2,
  barGap: 1,
  barRadius: 2,
});

// Example control implementation
const playBtn = document.getElementById('playBtn');
playBtn.addEventListener('click', () => {
  wavesurfer.playPause();
});

Handling Audio Load Events and Controls

Wavesurfer exposes several event listeners to handle playback states and user interaction. Common events include ready, play, pause, and finish.

wavesurfer.on('ready', () => {
  console.log('Audio waveform is ready to play.');
});

wavesurfer.on('finish', () => {
  console.log('Audio playback completed.');
});

When you are done using the instance or when unmounting a component in modern JavaScript frameworks, call wavesurfer.destroy() to clean up event listeners and free up browser resources.