Add Custom Property to Howl Object in Howler.js
This article explains how to attach custom properties to a
Howl object in the howler.js library. You will learn the
simplest methods to assign custom metadata, such as track IDs, custom
states, or descriptions, directly to your audio instances for better
state management in your web applications.
Method 1: Direct Property Assignment
Since JavaScript objects are dynamic, the easiest way to attach a
custom property to a Howl instance is through direct
assignment after instantiation. You can define any key-value pair
directly on the created object.
// Import or use Howler.js
const sound = new Howl({
src: ['audio.mp3']
});
// Attach custom properties directly
sound.customId = 'track_101';
sound.genre = 'Ambient';
sound.isUserFavorite = true;
// Access the properties later
console.log(sound.customId); // Outputs: track_101This approach is highly efficient and requires no additional configuration or wrapper functions.
Method 2: Extending the Howl Class
If you are building a larger application and want a more structured,
object-oriented approach, you can extend the Howl class
using ES6 inheritance. This allows you to define custom properties
inside a constructor.
class CustomHowl extends Howl {
constructor(options, customMetadata) {
super(options);
this.metadata = customMetadata;
}
}
// Instantiate the custom class
const track = new CustomHowl({
src: ['music.mp3']
}, {
id: 'track_102',
artist: 'John Doe',
album: 'Synthwave Dreams'
});
// Access the nested custom properties
console.log(track.metadata.artist); // Outputs: John DoeUsing inheritance ensures that all instances of your custom audio object follow a strict, predictable data structure.
Method 3: Using a Wrapper Object
If you prefer not to modify the library’s instantiated objects
directly, you can wrap the Howl instance inside a standard
JavaScript object. This keeps the library’s core object clean and
separates your application logic from the audio player state.
const audioTrack = {
howl: new Howl({ src: ['soundtrack.wav'] }),
id: 'track_103',
title: 'Main Theme',
tags: ['cinematic', 'orchestral']
};
// Control the audio through the wrapper
audioTrack.howl.play();
// Access the metadata
console.log(audioTrack.title); // Outputs: Main ThemeThis method is highly recommended if you are using state management libraries like Redux, Vuex, or Pinia, where keeping raw third-party instances separated from application state is best practice.