Set rolloffFactor for 3D Sound in Howler.js

This article explains how to configure the rolloffFactor for 3D spatial audio in Howler.js. You will learn how to access the panner attributes of a sound instance to control how quickly the volume decays as the audio source moves away from the listener.

Using the pannerAttr Method

Howler.js utilizes the Web Audio API’s PannerNode to handle 3D spatial audio. To modify spatial properties like the rolloffFactor, you must use the pannerAttr method on your Howl instance.

Note that spatial audio requires the Web Audio API, so you must ensure the html5 property is set to false (which is the default).

Code Example

Here is how to initialize a spatial sound, position it in 3D space, and set its rolloffFactor:

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

// 2. Play the sound to get its sound ID
const soundId = 3dSound.play();

// 3. Set the initial 3D position of the sound (X, Y, Z coordinates)
3dSound.pos(5, 0, -10, soundId);

// 4. Set the rolloffFactor using pannerAttr
3dSound.pannerAttr({
  rolloffFactor: 1.5,        // Determines the rate of attenuation (default is 1)
  distanceModel: 'inverse',  // 'linear', 'inverse', or 'exponential'
  refDistance: 1,            // Distance where volume reduction begins
  maxDistance: 1000          // Maximum distance before volume stops reducing
}, soundId);

How rolloffFactor Works

The rolloffFactor defines how fast the volume decreases as the sound source moves away from the listener.

The effect of the rolloffFactor is heavily dependent on the chosen distanceModel. For instance, with the 'linear' model, the volume drops linearly, whereas 'inverse' and 'exponential' models mimic real-world acoustics where sound drops off exponentially over distance.