How to Toggle Audio Playback in Wavesurfer.js

To toggle between playing and pausing audio in Wavesurfer.js, you use the playPause() method. Calling this method automatically checks the current playback status of the audio instance—if the audio is currently playing, it pauses it; if it is paused or stopped, it resumes playback from the current playhead position.

Using playPause() simplifies audio control logic because you do not need to manually check the playback state before executing a command. Here is a basic example of how to implement it with an HTML button:

// Initialize Wavesurfer instance
const wavesurfer = WaveSurfer.create({
    container: '#waveform',
    waveColor: '#4F46E5',
    progressColor: '#818CF8',
    url: '/path/to/audio.mp3'
});

// Select your toggle button
const playPauseBtn = document.getElementById('playPauseBtn');

// Toggle playback on click
playPauseBtn.addEventListener('click', () => {
    wavesurfer.playPause();
});

In addition to playPause(), Wavesurfer.js provides individual methods such as play() and pause() if you need explicit control over specific states. You can also listen to events like play and pause using wavesurfer.on('play', callback) to update user interface elements, such as changing a button icon dynamically when the playback state alters.