How to Use pannerAttr in Howler.js

This article provides a straightforward guide on how to use the pannerAttr property in howler.js to configure spatial 3D audio. You will learn what pannerAttr does, the specific properties it accepts, and how to implement it in your JavaScript code to customize sound spatialization, distance models, and roll-off factors.

To use 3D spatial audio in howler.js, you must use the spatial plugin (included in the default howler.js bundle). The pannerAttr property is used to define the physical characteristics of the sound source in a 3D space, mapping directly to the Web Audio API’s PannerNode.

Defining pannerAttr on Initialization

You can set the default spatial attributes when instantiating a new Howl object. The pannerAttr property accepts an object with several configuration options.

const sound = new Howl({
  src: ['audio.mp3'],
  html5: false, // Spatial audio requires Web Audio API
  pannerAttr: {
    coneInnerAngle: 360,
    coneOuterAngle: 360,
    coneOuterGain: 0,
    distanceModel: 'inverse',
    maxDistance: 1000,
    refDistance: 1,
    panningModel: 'HRTF',
    rolloffFactor: 1
  }
});

Key Properties of pannerAttr

Updating pannerAttr Dynamically

You can also get or set these properties dynamically after the sound has been created. To update the attributes of a playing sound, pass the new attributes object to the pannerAttr() method.

// Update panning attributes on the fly
sound.pannerAttr({
  distanceModel: 'exponential',
  rolloffFactor: 2,
  maxDistance: 500
});

// To apply the change to a specific sound instance, pass the sound ID
const soundId = sound.play();
sound.pannerAttr({
  rolloffFactor: 1.5
}, soundId);

To hear the effects of pannerAttr, you must also define the position of the sound using sound.pos(x, y, z) and the position of the listener using Howler.pos(x, y, z).