Set coneOuterGain for Howler.js Directional Audio
This article provides a straightforward guide on how to configure the
coneOuterGain property for spatialized, directional audio
sources in howler.js. You will learn how to use the Howler.js spatial
audio API to control the volume of a sound outside its directional cone,
allowing you to create realistic 3D soundscapes in your web
applications.
To set the coneOuterGain of a directional audio source
in Howler.js, you must use the pannerAttr method on your
Howl instance. This method configures the underlying Web
Audio API PannerNode properties, which control how sound
behaves in 3D space.
Prerequisites
For spatial audio to work in Howler.js: 1. You must use the spatial
plugin (included in the default howler.js or
howler.spatial.js build). 2. The html5
property of the Howl instance must be set to
false (Web Audio API is required for spatial effects).
Step-by-Step Implementation
1. Initialize the Howl Instance
Define your sound source and ensure Web Audio is enabled by setting
html5: false.
const sound = new Howl({
src: ['soundtrack.mp3'],
html5: false // Required for spatial/3D audio
});2. Play the Sound and Get the Sound ID
Spatial properties are applied to specific playback instances using their unique sound ID.
const soundId = sound.play();3. Define Position and Orientation
For directional cones to work, the sound source must have both a position in 3D space and an orientation vector pointing in a specific direction.
// Position the sound at the center of the 3D space (X, Y, Z)
sound.pos(0, 0, 0, soundId);
// Point the sound source forward along the Z-axis (X, Y, Z)
sound.orientation(0, 0, 1, soundId);4. Configure
pannerAttr with coneOuterGain
Use the pannerAttr method to set
coneOuterGain alongside coneInnerAngle and
coneOuterAngle.
sound.pannerAttr({
coneInnerAngle: 90, // No attenuation occurs inside this angle (in degrees)
coneOuterAngle: 180, // Attenuation begins transitioning outside this angle
coneOuterGain: 0.1 // The volume level (0.0 to 1.0) outside the outer cone
}, soundId);Understanding the Properties
coneInnerAngle: A 3D cone, in degrees, inside of which there is no volume attenuation.coneOuterAngle: A 3D cone, in degrees, outside of which the volume is attenuated by a constant factor defined byconeOuterGain.coneOuterGain: A value between0.0(complete silence) and1.0(no attenuation). This value determines the volume level of the audio when the listener is completely outside theconeOuterAngle. Setting this to0.1means the sound drops to 10% volume when you stand behind the directional source.