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
coneInnerAngle: A parameter (in degrees) defining a 3D cone in which there is no volume reduction. The default is360.coneOuterAngle: A parameter (in degrees) defining a 3D cone outside of which the volume is reduced by a constant value defined byconeOuterGain. The default is360.coneOuterGain: The amount of volume reduction outside theconeOuterAngle. It ranges from0.0to1.0. The default is0.distanceModel: Determines the algorithm used to reduce the volume as the audio source moves away from the listener. Acceptable values are'linear','inverse', or'exponential'. The default is'inverse'.maxDistance: The maximum distance between the source and the listener, after which the volume is no longer reduced. The default is10000.refDistance: The reference distance for reducing volume as the audio source moves further from the listener. The default is1.panningModel: The spatialization algorithm used to position the audio in 3D space. Options are'HRTF'(high quality, simulates binaural hearing) or'equalpower'(faster, less resource-intensive). The default is'HRTF'.rolloffFactor: Describes how quickly the volume decreases as the source moves away from the listener. The default is1.
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).