Work with audio in JavaScript using Howler.js

Reference JavaScript

Share

In this tutorial we will learn about Howler.js which makes working with audio in JavaScript easy and reliable across all platforms.

Click here to visit Howler.js GitHub repository.

Install

If you have Node and NPM installed then use the following command in the terminal to get howler as a dependency in your project.

npm install howler --save

Or, get the latest release from Howeler.js GitHub repository.

Or, get it from CDN like cdnjs and jsDelivr.

Step 1: Include the script

Include the howler.js script in the page.

<script src="path/to/howler.js"></script>

Step 2: Instantiate and configure Howler

Now, its time to instantiate Howler and configure it to play audio files.

In the following example we are including an audio file audio.mp3 and setting the volume which can have value between 0 to 1. And then we are playing the audio using the play() method.

var sound = new Howl({
  src: ['path/to/audio.mp3'],
  volume: 0.8
});

sound.play();

Example


Audio courtsey: sample-videos.com


The Play button runs the play() method which starts the playback of the sound.

The Pause button runs the pause() method which pauses the playback of the sound.

The Stop button runs the stop() method which stops the playback of the sound and resets the seek to 0. So, if the audio is played for 5 seconds and Stop button is clicked then the seek is reset to 0 second and when the audio is played again it starts from 0.

The Vol+ button increases the volume and the Vol- button decreases the volume.

HTML

<button id='howler-play'>Play</button>
<button id='howler-pause'>Pause</button>
<button id='howler-stop'>Stop</button>
<button id='howler-volup'>Vol+</button>
<button id='howler-voldown'>Vol-</button>

JavaScript

Note! Using jQuery in the following example.

$(function(){

	var howler_example = new Howl({
		src: ['/audio/sample/SampleAudio_0.4mb.mp3'],
		volume: 0.5
	});

	$("#howler-play").on("click", function(){
		howler_example.play();
	});

	$("#howler-pause").on("click", function(){
		howler_example.pause();
	});

	$("#howler-stop").on("click", function(){
		howler_example.stop();
	});

	$("#howler-volup").on("click", function(){
		var vol = howler_example.volume();
		vol += 0.1;
		if (vol > 1) {
			vol = 1;
		}
		howler_example.volume(vol);
	});

	$("#howler-voldown").on("click", function(){
		var vol = howler_example.volume();
		vol -= 0.1;
		if (vol < 0) {
			vol = 0;
		}
		howler_example.volume(vol);
	});

});
Share

Recently Updated