How to Play an Audio Track in Howler.js
Howler.js is a robust JavaScript audio library that simplifies web
audio playback across different browsers. This guide provides a
straightforward, step-by-step walkthrough on how to initialize the
library, load an audio file, and control playback using the
Howl object.
Step 1: Include Howler.js in Your Project
To use Howler.js, you must first include the library in your HTML
file. You can load it directly from a CDN by adding the following script
tag to your <head> or before the closing
</body> tag:
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.2.3/howler.min.js"></script>Alternatively, if you are using a package manager like npm, you can
install it using npm install howler and import it into your
JavaScript file:
import { Howl, Howler } from 'howler';Step 2: Define and Play the Audio Track
To play an audio track, you need to create a new instance of the
Howl object. Pass an configuration object containing the
src property, which points to the path of your audio
file.
Once initialized, call the .play() method on your
instance.
// Define the audio track
const sound = new Howl({
src: ['path/to/your-audio-file.mp3'],
html5: true // Forces HTML5 Audio, recommended for large files/streaming
});
// Play the audio track
sound.play();Basic Audio Controls
Howler.js allows you to control the playback of your audio track easily with the following built-in methods:
Pause playback:
sound.pause();Stop playback (this pauses the audio and resets the playback position to 0):
sound.stop();Adjust volume (values range from
0.0to1.0):sound.volume(0.5); // Sets volume to 50%Loop the audio: You can set the audio to loop automatically by adding the
loopproperty to the configuration:const sound = new Howl({ src: ['audio.mp3'], loop: true });