Howler.js Spatial Audio distanceModel Explained

In modern web development, creating immersive 3D audio environments requires precise control over how sound behaves over distances. This article explains the distanceModel attribute in Howler.js, a popular JavaScript audio library. You will learn what the distanceModel attribute is, how it controls audio attenuation in spatial audio environments, and how to configure its various algorithms to achieve realistic 3D soundscapes.

What is the distanceModel Attribute?

In Howler.js, the distanceModel attribute determines the algorithm used to reduce the volume (attenuate) of a sound source as it moves further away from the listener. It is a direct binding to the Web Audio API’s PannerNode.distanceModel property.

When positioning audio in a 3D space, simply moving a sound to the left or right is not enough; the sound must also get quieter as the virtual distance between the listener and the audio source increases. The distanceModel defines the mathematical formula that calculates this volume reduction.

The Three Distance Models

Howler.js supports three distinct distance models, each suited for different acoustic scenarios:

1. Linear Model ('linear')

The linear model decreases the volume at a constant rate relative to the distance between the listener and the sound source.

2. Inverse Model ('inverse')

The inverse model decreases the volume inversely proportional to the distance. This is the default model used by Howler.js.

3. Exponential Model ('exponential')

The exponential model decreases the volume at an exponential rate.

Configuring distanceModel in Howler.js

To utilize spatial audio and configure the distanceModel in Howler.js, you must ensure that your sound is loaded using the Web Audio API (by default, html5: false) and use the pannerAttr method on your Howl instance.

Here is a practical example of how to implement and configure the distanceModel:

// Initialize a spatial sound
const 3dSound = new Howl({
  src: ['ambient_space.mp3'],
  html5: false // Must be false to use the Web Audio API spatial features
});

// Configure the spatial attributes
3dSound.pannerAttr({
  distanceModel: 'inverse', // Options: 'linear', 'inverse', 'exponential'
  refDistance: 1,           // The distance at which volume starts to reduce
  maxDistance: 1000,        // The distance past which volume stops reducing
  rolloffFactor: 1          // How quickly the volume fades
});

// Position the sound in 3D space (X, Y, Z coordinates)
3dSound.pos(5, 0, -10);

// Play the sound
3dSound.play();

Supporting Attributes

The distanceModel does not work in isolation. Its behavior is directly scaled and modified by three other key properties inside the pannerAttr object: