How to Pause Sound in Howler.js
This article provides a quick and practical guide on how to pause
currently playing audio in howler.js. You will learn how to use the
pause() method to halt playback for a single sound instance
or an entire sound object, as well as how to resume the audio from where
it was paused.
To pause a sound in howler.js, you use the .pause()
method on your Howl instance. Howler.js allows you to
either pause all playing instances of a specific sound or target a
single instance using its unique sound ID.
Pausing a Sound Instance
When you call the .play() method, it returns a unique
sound ID. You can pass this ID to the .pause() method to
pause that specific instance of the sound. This is useful when you have
the same sound effect playing multiple times simultaneously.
// Define the sound
const sound = new Howl({
src: ['audio.mp3']
});
// Play the sound and store its unique ID
const soundId = sound.play();
// Pause this specific sound instance
sound.pause(soundId);Pausing All Instances of a Howl Object
If you want to pause all active playbacks of a specific
Howl object at once, simply call the .pause()
method without passing any arguments.
// Play the sound multiple times
sound.play();
sound.play();
// Pause all active playbacks of this sound
sound.pause();Resuming a Paused Sound
To resume playback from where the audio was paused, use the
.play() method again. If you paused a specific instance,
pass the sound ID to resume only that instance. If you paused the entire
object, calling .play() without arguments will play it from
the beginning or resume the last paused instance depending on your
setup.
// Resume the specific paused sound instance
sound.play(soundId);