What is PannerNode?
PannerNode is a powerful AudioNode that positions audio sources in three-dimensional space, enabling immersive spatial audio experiences. Part of the Web Audio API, it simulates how sound travels in physical environments, making it essential for games, virtual reality, and interactive web applications.
As a core component of the Web Audio API architecture, PannerNode uses a right-hand Cartesian coordinate system to define where sounds originate and how they interact with the listener's position. Unlike simple stereo panning that only moves sound left and right, PannerNode can place audio anywhere in 3D space--above, below, in front, behind, and at varying distances.
This capability opens possibilities for creating convincing audio environments where users can perceive the direction and distance of sound sources, just as they would in the real world. Whether you're building an immersive game, a virtual meeting space, or an interactive educational experience, PannerNode provides the foundation for realistic audio positioning as part of your web development toolkit.
Key features that make spatial audio possible
3D Positioning
Place audio sources anywhere in three-dimensional space using Cartesian coordinates
Panning Models
Choose between HRTF for realistic spatial audio or equalpower for simple stereo positioning
Distance Attenuation
Control how volume changes as sound sources move closer or farther away
Directional Cones
Create directional audio sources with configurable inner and outer cone angles
Stereo Output
Always outputs stereo audio for realistic spatial perception
Browser Support
Widely supported across all modern browsers since 2015
Creating a PannerNode
The PannerNode constructor takes an audio context and an optional configuration object. This allows you to set up the spatial audio properties at creation time, or configure them dynamically as your application runs.
Constructor Syntax
const panner = new PannerNode(context);
const panner = new PannerNode(context, options);
Constructor Parameters
The context parameter is required and specifies the BaseAudioContext to associate with the node. The optional options object allows you to configure all spatial properties upfront, including position, orientation, panning model, and distance model settings.
PannerOptions Properties
| Property | Default | Description |
|---|---|---|
| panningModel | "equalpower" | Spatialization algorithm (equalpower or HRTF) |
| distanceModel | "inverse" | Volume reduction algorithm (linear, inverse, exponential) |
| positionX | 0 | Horizontal position in 3D space |
| positionY | 0 | Vertical position in 3D space |
| positionZ | 0 | Depth position in 3D space |
| orientationX | 1 | Source direction vector X component |
| orientationY | 0 | Source direction vector Y component |
| orientationZ | 0 | Source direction vector Z component |
| refDistance | 1 | Reference distance for distance-based attenuation |
| maxDistance | 10000 | Maximum distance for attenuation |
| rolloffFactor | 1 | How quickly volume decreases with distance |
| coneInnerAngle | 360 | Angle of full-volume cone in degrees |
| coneOuterAngle | 360 | Angle of outer cone in degrees |
| coneOuterGain | 0 | Volume multiplier outside outer cone |
Example: Creating a Configured PannerNode
const audioCtx = new AudioContext();
const panner = new PannerNode(audioCtx, {
panningModel: 'HRTF',
distanceModel: 'inverse',
positionX: 0,
positionY: 0,
positionZ: -5,
refDistance: 1,
maxDistance: 10000,
rolloffFactor: 1,
coneInnerAngle: 360,
coneOuterAngle: 360,
coneOuterGain: 0
});
// Connect to the audio graph
source.connect(panner);
panner.connect(audioCtx.destination);
Panning Models
The panning model determines how PannerNode calculates the stereo output based on the source's position relative to the listener. Choosing the right model affects both audio quality and CPU usage.
Equalpower
The equalpower model is a simple panning algorithm that distributes audio between left and right channels based on position. It's the default for backwards compatibility and works well for straightforward left-right positioning without full 3D spatialization.
Best for:
- Simple UI sound effects
- Background audio that doesn't require immersive positioning
- Applications where CPU usage is a concern
- Basic left-right stereo panning
HRTF
HRTF (Head-Related Transfer Function) creates physically-based spatialization by simulating how human ears perceive sound direction. This produces much more realistic 3D audio positioning, allowing users to perceive sounds not just left and right, but also front, back, above, and below.
Best for:
- Games and virtual reality experiences
- Immersive audio applications
- Applications where audio quality is paramount
- When creating convincing spatial soundscapes
// Recommended: Use HRTF for better spatial audio
const panner = new PannerNode(audioCtx, {
panningModel: 'HRTF',
positionX: 2,
positionY: 1,
positionZ: -3
});
The HRTF model uses convolution processing to create binaural audio that accounts for how your head and ears shape incoming sound waves. This creates the perception of sounds coming from specific 3D locations, making it ideal for immersive experiences. For applications requiring cutting-edge audio capabilities, consider how AI-powered web experiences can further enhance user engagement.
However, HRTF is more computationally expensive than equalpower. For simple applications or devices with limited processing power, equalpower may be the better choice. Consider your application's requirements when selecting a panning model.
Distance Models
Distance models control how the volume of an audio source changes as it moves further from the listener. This mimics how sound behaves in the real world--things that are farther away sound quieter.
Inverse Model
The inverse model follows the physics of how sound intensity decreases with distance. It's the default and works well for most applications, creating a natural-sounding falloff as sounds move away.
Formula: gain = refDistance / (refDistance + rolloffFactor × (distance - refDistance))
Best for: Most general-purpose spatial audio applications
Linear Model
The linear model creates a gradual, predictable volume reduction over distance. The volume decreases at a constant rate from refDistance to maxDistance.
Formula: gain = 1 - rolloffFactor × (distance - refDistance) / (maxDistance - refDistance)
Best for: Applications needing predictable attenuation or game audio with controlled falloff zones
Exponential Model
The exponential model creates more dramatic distance effects, with volume dropping off quickly at first and then more gradually. The squared version provides even more pronounced distance perception.
Formula: gain = (refDistance / (refDistance + rolloffFactor × (distance - refDistance)))²
Best for: Dramatic audio effects or outdoor environmental sounds
Key Distance Properties
refDistance sets where attenuation begins. Sounds closer than this distance play at full volume. Set it based on your virtual environment's scale--1 unit might work for a small room, while 10 units works better for larger spaces.
maxDistance defines where attenuation stops. Beyond this point, the volume stays constant at the reduced level. Set this to match the largest distance in your audio scene.
rolloffFactor controls how quickly volume decreases. Higher values mean faster falloff. Values between 0.5 and 2 work for most scenarios, but can be adjusted for special effects.
Position and Orientation
Understanding how to set position and orientation is crucial for placing audio sources where you want them in the 3D soundscape.
The Coordinate System
PannerNode uses a right-hand Cartesian coordinate system where:
- X-axis runs left to right (negative is left, positive is right)
- Y-axis runs up and down (negative is down, positive is up)
- Z-axis runs front to back (negative is in front, positive is behind)
The listener's position is typically at the origin (0, 0, 0), and audio sources are positioned relative to this point.
Setting Position
// Position sound 3 units to the right, 1 unit up, 5 units in front
panner.positionX.value = 3;
panner.positionY.value = 1;
panner.positionZ.value = -5;
// Or using scheduled updates for smooth transitions
panner.positionX.setValueAtTime(0, audioCtx.currentTime);
panner.positionX.linearRampToValueAtTime(5, audioCtx.currentTime + 2);
Setting Orientation
The orientation properties define which direction the audio source is pointing. This is important for creating directional audio sources--think of a speaker cone that projects sound in a specific direction rather than equally in all directions.
// Point the sound downward
panner.orientationX.value = 0;
panner.orientationY.value = -1;
panner.orientationZ.value = 0;
// Point the sound forward and slightly down
panner.orientationX.value = 0;
panner.orientationY.value = -0.5;
panner.orientationZ.value = -1;
AudioParam Automation
PannerNode's position and orientation properties are AudioParams, which means you can automate their values over time for moving sounds or animated audio sources:
const now = audioCtx.currentTime;
// Smoothly move sound from left to right over 3 seconds
panner.positionX.setValueAtTime(-5, now);
panner.positionX.linearRampToValueAtTime(5, now + 3);
// Or create a circular motion
function animateSoundInCircle() {
const time = audioCtx.currentTime;
panner.positionX.value = Math.cos(time) * 3;
panner.positionZ.value = Math.sin(time) * 3;
requestAnimationFrame(animateSoundInCircle);
}
Cone-Based Directional Audio
The cone properties let you create directional audio sources--sources that project sound in a specific direction rather than equally in all directions. This mimics real-world directional sound sources like speakers, musical instruments, or flashlights.
How the Sound Cone Works
PannerNode projects sound in a cone-shaped area extending from the source in the direction of the orientation vector:
- Inner Cone: The area within this angle receives full volume (no reduction)
- Outer Cone: The area between inner and outer cone angles has gradual volume reduction
- Beyond Outer Cone: Sound is reduced by the coneOuterGain factor
Configuring the Cone
// Create a directional source like a stage speaker
panner.coneInnerAngle = 45; // Full volume within 45 degrees
panner.coneOuterAngle = 90; // Gradual reduction between 45-90 degrees
panner.coneOuterGain = 0.3; // 30% volume outside the cone
Practical Applications
Stage Monitors: Point the cone toward the performer so they hear their own audio while the audience hears it from the main speakers.
Voice Chat in Virtual Spaces: Use a narrow cone so users only hear nearby voices when facing each other.
Environmental Sounds: Create realistic outdoor sounds where noise comes from a specific direction (traffic, wind, wildlife).
Game Audio: Position enemy footsteps or warnings with directional cones to create spatial awareness. These techniques are commonly used by professional web development teams building interactive gaming experiences.
Example: Pointing a Sound Source
const panner = new PannerNode(audioCtx, {
positionX: 0,
positionY: 2, // Sound source on ceiling
positionZ: 0,
orientationX: 0, // Pointing straight down
orientationY: -1,
orientationZ: 0,
coneInnerAngle: 30,
coneOuterAngle: 60,
coneOuterGain: 0.2
});
Integrating with AudioListener
For complete spatial audio, PannerNode works in conjunction with the AudioListener, which represents the user (or their ears) in the 3D space. The relative positions of the listener and panner nodes determine where sounds appear to come from.
Setting Up the Listener
The listener is accessed from the audio context and has position and orientation properties that define where the user is and which way they're facing:
const listener = audioCtx.listener;
// Position the listener at the origin
listener.positionX.value = 0;
listener.positionY.value = 0;
listener.positionZ.value = 0;
// Define the listener's forward direction
listener.forwardX.value = 0;
listener.forwardY.value = 0;
listener.forwardZ.value = -1; // Facing forward
// Define the top of the listener's head
listener.upX.value = 0;
listener.upY.value = 1;
listener.upZ.value = 0; // Head pointing up
How Listener and Panner Interact
The perceived position of a sound is calculated from the relative positions of the panner and listener. When you move the listener, sounds that were "in front" might now appear "behind"--just like in real life when you turn your head.
Practical Example: First-Person Audio
// Set up a first-person perspective
const listener = audioCtx.listener;
// Listener starts at origin
listener.positionX.value = 0;
listener.positionY.value = 1.7; // Average ear height
listener.positionZ.value = 0;
// Place a sound source in front of the listener
const panner = new PannerNode(audioCtx, {
positionX: 0,
positionY: 1.7,
positionZ: -5, // 5 units in front
panningModel: 'HRTF'
});
// When the listener turns right...
listener.forwardX.value = 1;
listener.forwardZ.value = 0;
// The sound now appears to come from the left
Dynamic Listener Updates
For games and VR applications, you update the listener position and orientation based on user movement:
function updateListenerPosition(cameraPosition, cameraRotation) {
const listener = audioCtx.listener;
listener.positionX.value = cameraPosition.x;
listener.positionY.value = cameraPosition.y;
listener.positionZ.value = cameraPosition.z;
// Convert rotation to forward vector
listener.forwardX.value = Math.sin(cameraRotation);
listener.forwardZ.value = -Math.cos(cameraRotation);
}
Complete Code Examples
Basic 3D Audio Setup
// Initialize the audio context
const audioCtx = new AudioContext();
// Create a media element source
const audioElement = document.querySelector('audio');
const source = audioCtx.createMediaElementSource(audioElement);
// Create a PannerNode with spatial audio
const panner = new PannerNode(audioCtx, {
panningModel: 'HRTF',
distanceModel: 'inverse',
positionX: 0,
positionY: 0,
positionZ: -5,
refDistance: 1,
rolloffFactor: 1
});
// Connect the audio graph
source.connect(panner);
panner.connect(audioCtx.destination);
// Play the audio
audioElement.play();
Moving Sound Source
// Create a panner for a moving sound
const movingPanner = new PannerNode(audioCtx, {
panningModel: 'HRTF',
positionX: 0,
positionY: 1,
positionZ: 0
});
// Animate the sound moving in a circle
function animatePanner() {
const time = audioCtx.currentTime;
const radius = 3;
const speed = 0.5;
movingPanner.positionX.value = Math.cos(time * speed) * radius;
movingPanner.positionZ.value = Math.sin(time * speed) * radius;
requestAnimationFrame(animatePanner);
}
// Start animation
animatePanner();
Multiple Spatial Sources
// Create multiple positioned audio sources
function createSpatialSource(url, x, y, z) {
const audio = new Audio(url);
const source = audioCtx.createMediaElementSource(audio);
const panner = new PannerNode(audioCtx, {
panningModel: 'HRTF',
positionX: x,
positionY: y,
positionZ: z,
refDistance: 1,
rolloffFactor: 1
});
source.connect(panner);
panner.connect(audioCtx.destination);
return { element: audio, panner };
}
// Place sounds around the listener
const sources = [
createSpatialSource('voice1.mp3', -3, 0, -2),
createSpatialSource('voice2.mp3', 3, 0, -2),
createSpatialSource('ambient.mp3', 0, 2, -4)
];
// Play all sources
sources.forEach(s => s.element.play());
Performance Best Practices
Optimizing PannerNode usage ensures smooth audio without impacting application performance.
Model Selection Guidelines
| Use Case | Panning Model | Distance Model | Notes |
|---|---|---|---|
| Games/VR | HRTF | inverse | Best quality for immersion |
| Simple UI sounds | equalpower | linear | Lower CPU usage |
| Background ambient | equalpower | exponential | Natural outdoor feel |
| Virtual meetings | HRTF | inverse | Clear spatial positioning |
Optimize Position Updates
- Batch updates: Instead of updating every frame, use AudioParam automation methods like
linearRampToValueAtTimeorsetValueAtTimewith scheduled times - Throttle unnecessary updates: Only update when the position actually changes
- Use AudioWorklets: For complex animations, consider moving position logic to an AudioWorklet for more precise timing
// Efficient: Scheduled updates
const now = audioCtx.currentTime;
panner.positionX.setValueAtTime(startPos, now);
panner.positionX.linearRampToValueAtTime(endPos, now + 2);
// Avoid: Per-frame updates
function badExample() {
panner.positionX.value = newValue; // Called every frame
}
Resource Management
Proper cleanup prevents memory leaks and audio issues:
// When done with a panner, disconnect it
panner.disconnect();
// Or when closing the entire context
async function cleanup() {
await audioCtx.close();
}
Coordinate Space Considerations
- Keep your coordinate scale consistent throughout the scene
- A unit of 1 meter works well for most applications
- If using different scales, adjust refDistance and maxDistance accordingly
- Consider the listener's position relative to the scene bounds
Testing Spatial Audio
Always test spatial audio with stereo headphones, as the effect relies on hearing different channels in each ear. Computer speakers or mono audio will not demonstrate the 3D positioning effect.
Frequently Asked Questions
What's the difference between PannerNode and StereoPannerNode?
PannerNode creates full 3D spatial audio with depth perception, while StereoPannerNode only handles left-right panning. Use PannerNode for immersive experiences and StereoPannerNode for simple balance control.
Do I need special equipment to hear spatial audio?
Stereo headphones are essential to perceive 3D positioning. Computer speakers cannot reproduce the left-right channel differences needed for spatial perception.
Which panning model should I choose?
Use HRTF for games, VR, and any application where audio quality matters. Use equalpower for simple UI sounds or when CPU usage is a concern.
How do I handle the user turning their head in VR?
Update the AudioListener's forward orientation based on the device's orientation sensors. The PannerNode positions will automatically recalculate relative to the new listener orientation.
Can I animate PannerNode positions smoothly?
Yes, use AudioParam automation methods like linearRampToValueAtTime, exponentialRampToValueAtTime, or setValueAtTime for smooth transitions between positions.
Conclusion
PannerNode is essential for creating immersive web audio experiences that rival native applications. By understanding its core capabilities--3D positioning, configurable panning and distance models, and directional cones--you can build audio experiences that feel natural and engaging.
The key to success with PannerNode lies in choosing the right configuration for your use case. HRTF provides the most realistic spatial audio for games and VR, while equalpower offers a lightweight alternative for simpler applications. Combined with proper distance modeling and listener integration, PannerNode opens a world of possibilities for web-based audio.
Remember to test with stereo headphones, optimize position updates for performance, and consider your users' device capabilities when selecting panning models. With these considerations in mind, PannerNode becomes a powerful tool for creating compelling audio experiences on the web. Our web development team can help you implement these techniques for your next project.