How to Load Audio into Wavesurfer.js via URL

Loading an audio file into Wavesurfer.js using a URL is a straightforward process that involves initializing the WaveSurfer instance and calling its load method with the audio file link. Wavesurfer.js fetches the audio via HTTP, decodes the buffer, and automatically renders the waveform on an HTML container element.

Wavesurfer.js is a popular, open-source JavaScript library that uses the Web Audio API and HTML5 Canvas to render interactive audio waveforms in web applications. To load audio from a URL, you first need to create a container element in your HTML document and instantiate the WaveSurfer object.

Here is a step-by-step implementation in standard JavaScript:

  1. Create a container element in HTML:
<div id="waveform"></div>
  1. Initialize WaveSurfer and pass the target URL to the load method:
import WaveSurfer from 'wavesurfer.js'

const wavesurfer = WaveSurfer.create({
  container: '#waveform',
  waveColor: '#4F46E5',
  progressColor: '#818CF8',
  url: 'https://example.com/audio-file.mp3'
})

In modern versions of Wavesurfer.js (v7 and above), you can pass the url option directly inside the initial configuration object. Wavesurfer.js will fetch and render the waveform automatically upon initialization.

Alternatively, if you prefer to initialize the instance first and load the audio track dynamically later, you can use the explicit load method:

const wavesurfer = WaveSurfer.create({
  container: '#waveform',
  waveColor: '#4F46E5',
  progressColor: '#818CF8'
})

wavesurfer.load('https://example.com/audio-file.mp3')

When loading audio files hosted on a different domain, ensure that the remote server has Cross-Origin Resource Sharing (CORS) headers configured properly. If CORS is restricted on the server hosting the audio file, the Web Audio API will fail to decode the audio stream and throw a network error in the browser console.