How Do You Pause Audio Playback in Wavesurfer.js?
Pausing audio playback in a Wavesurfer.js instance is achieved
primarily by calling the native pause() method on your
initialized Wavesurfer object. Alternatively, developers can utilize the
playPause() method to toggle between play and pause states,
or handle playback dynamically by listening to key events or custom UI
control actions.
Using the standard
pause() method
The most direct way to stop playback without resetting the audio
playhead is calling the .pause() method directly on your
Wavesurfer instance. This halts audio playback immediately at the
current frame and updates the internal state.
// Initialize Wavesurfer instance
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: '#4F46E5',
progressColor: '#818CF8',
url: '/path-to-audio.mp3',
});
// Pause playback on demand
function pauseAudio() {
wavesurfer.pause();
}Toggling playback with
playPause()
If you are binding controls to a single button, such as a master
Play/Pause toggle, use the playPause() method. It
automatically checks the current playback state and pauses the audio if
it is playing, or starts it if it is paused.
const toggleButton = document.querySelector('#playPauseBtn');
toggleButton.addEventListener('click', () => {
wavesurfer.playPause();
});Listening to pause events
Wavesurfer.js emits state events whenever playback changes. You can
attach an event listener to the pause event to execute
custom UI logic, such as updating button icons or stopping animation
loops, whenever audio stops.
wavesurfer.on('pause', () => {
console.log('Audio playback has been paused.');
// Perform UI updates here, such as changing a button label
});