Adding 3D Sound to WebGL Scenes with the Web Audio API

The Web Audio API's AudioPannerNode brings 3D audio to WebGL applications. This node lets you define the position, orientation, and velocity of a sound source, while the audio context's listener attribute does the same for the listener. Together, these controls support directional sounds, doppler effects, and 3D panning.

// Detect if the audio context is supported.
window.AudioContext = (
  window.AudioContext ||
  window.webkitAudioContext ||
  null
);

if (!AudioContext) {
  throw new Error("AudioContext not supported!");
} 

// Create a new audio context.
var ctx = new AudioContext();

// Create a AudioGainNode to control the main volume.
var mainVolume = ctx.createGain();
// Connect the main volume node to the context destination.
mainVolume.connect(ctx.destination);

// Create an object with a sound source and a volume control.
var sound = {};
sound.source = ctx.createBufferSource();
sound.volume = ctx.createGain();

// Connect the sound source to the volume control.
sound.source.connect(sound.volume);
// Hook up the sound volume control to the main volume.
sound.volume.connect(mainVolume);

// Make the sound source loop.
sound.source.loop = true;

// Load a sound file using an ArrayBuffer XMLHttpRequest.
var request = new XMLHttpRequest();
request.open("GET", soundFileName, true);
request.responseType = "arraybuffer";
request.onload = function(e) {

  // Create a buffer from the response ArrayBuffer.
  ctx.decodeAudioData(this.response, function onSuccess(buffer) {
    sound.buffer = buffer;

    // Make the sound source use the buffer and start playing it.
    sound.source.buffer = sound.buffer;
    sound.source.start(ctx.currentTime);
  }, function onFailure() {
    alert("Decoding the audio buffer failed");
  });
};
request.send();

Position and Listener Tracking

At its core, positional audio uses the relative positions of sound sources and the listener to determine speaker mixing. A source left of the listener is louder in the left speaker.

To start, create an audio source and connect it to an AudioPannerNode, then set that node's position. Since the audio context listener defaults to (0,0,0), the panner position is initially camera-relative. To make positions world-relative, set the listener position to your camera position each frame.

...
sound.panner = ctx.createPanner();
// Instead of hooking up the volume to the main volume, hook it up to the panner.
sound.volume.connect(sound.panner);
// And hook up the panner to the main volume.
sound.panner.connect(mainVolume);
...

Using Three.js, a typical frame update tracks the panner node and listener positions:

...
// In the frame handler function, get the object's position.
object.position.set(newX, newY, newZ);
object.updateMatrixWorld();
var p = new THREE.Vector3();
p.setFromMatrixPosition(object.matrixWorld);

// And copy the position over to the sound of the object.
sound.panner.setPosition(p.x, p.y, p.z);
...
...
// Get the camera position.
camera.position.set(newX, newY, newZ);
camera.updateMatrixWorld();
var p = new THREE.Vector3();
p.setFromMatrixPosition(camera.matrixWorld);

// And copy the position over to the listener.
ctx.listener.setPosition(p.x, p.y, p.z);
...

Doppler Effect and Velocity

Velocity properties on both the listener and panner node create doppler effects. The simplest approach is computing per-frame velocities: the listener's velocity is the camera's current position minus its previous position, with the same logic applied to each audio source.

In Three.js, tracking velocity involves subtracting previous World positions from current ones and dividing by elapsed time:

...
var dt = secondsSinceLastFrame;

var p = new THREE.Vector3();
p.setFromMatrixPosition(object.matrixWorld);
var px = p.x, py = p.y, pz = p.z;

object.position.set(newX, newY, newZ);
object.updateMatrixWorld();

var q = new THREE.Vector3();
q.setFromMatrixPosition(object.matrixWorld);
var dx = q.x-px, dy = q.y-py, dz = q.z-pz;

sound.panner.setPosition(q.x, q.y, q.z);
sound.panner.setVelocity(dx/dt, dy/dt, dz/dt);
...

Directional Audio with Orientation

Orientation simulates directional sources, like a speaker being louder from the front. Critically, listener orientation determines whether a sound comes from your left or right. When you turn around, the left-right mixing must swap.

For a panner node's orientation vector, extract the rotation from the sound-emitting object's model matrix and multiply it against vec3(0,0,1). The listener orientation needs both a forward vector from the camera's rotation and an up vector for roll calculation; in Three.js this involves zeroing the translation parts of the world matrices before multiplication:

...
var vec = new THREE.Vector3(0,0,1);
var m = object.matrixWorld;

// Save the translation column and zero it.
var mx = m.elements[12], my = m.elements[13], mz = m.elements[14];
m.elements[12] = m.elements[13] = m.elements[14] = 0;

// Multiply the 0,0,1 vector by the world matrix and normalize the result.
vec.applyProjection(m);
vec.normalize();

sound.panner.setOrientation(vec.x, vec.y, vec.z);

// Restore the translation column.
m.elements[12] = mx;
m.elements[13] = my;
m.elements[14] = mz;
...
...
// The camera's world matrix is named "matrix".
var m = camera.matrix;

var mx = m.elements[12], my = m.elements[13], mz = m.elements[14];
m.elements[12] = m.elements[13] = m.elements[14] = 0;

// Multiply the orientation vector by the world matrix of the camera.
var vec = new THREE.Vector3(0,0,1);
vec.applyProjection(m);
vec.normalize();

// Multiply the up vector by the world matrix.
var up = new THREE.Vector3(0,-1,0);
up.applyProjection(m);
up.normalize();

// Set the orientation and the up-vector for the listener.
ctx.listener.setOrientation(vec.x, vec.y, vec.z, up.x, up.y, up.z);

m.elements[12] = mx;
m.elements[13] = my;
m.elements[14] = mz;
...

Orientation only affects audio when a cone is defined. Set the inner angle, outer angle, and outer gain in degrees (0–360); sound plays at normal volume inside the inner angle, fades to outer gain toward the outer angle, and stays at outer gain beyond it:

...
sound.panner.coneInnerAngle = innerAngleInDegrees;
sound.panner.coneOuterAngle = outerAngleInDegrees;
sound.panner.coneOuterGain = outerGainFactor;
...

Environmental Effects with ConvolverNodes

Once positional audio works, the ConvolverNode adds environmental realism. Default settings sound like an outdoor scene; a cathedral interior requires impulse response samples to match visuals with audio. Impulse responses are available online or can be self-recorded, though capturing them is involved.

Using a ConvolverNode requires rewiring the audio graph. Instead of audio passing directly to the main volume, route it to a pass-through mixer first, then branch to the ConvolverNode and to a plain audio gain. Each branch has its own GainNode so you can balance dry and effected signal before both connect to the main volume controller:

...
var ctx = new webkitAudioContext();
var mainVolume = ctx.createGain();

// Create a convolver to apply environmental effects to the audio.
var convolver = ctx.createConvolver();

// Create a mixer that receives sound from the panners.
var mixer = ctx.createGain();

sounds.forEach(function(sound){
  sound.panner.connect(mixer);
});

// Create volume controllers for the plain audio and the convolver.
var plainGain = ctx.createGain();
var convolverGain = ctx.createGain();

// Send audio from the mixer to plainGain and the convolver node.
mixer.connect(plainGain);
mixer.connect(convolver);

// Hook up the convolver to its volume control.
convolver.connect(convolverGain);

// Send audio from the volume controls to the main volume control.
plainGain.connect(mainVolume);
convolverGain.connect(mainVolume);

// Finally, connect the main volume to the audio context's destination.
volume.connect(ctx.destination);
...

Loading an impulse response follows standard Web Audio buffer loading patterns; load the sample, then assign the buffer to the ConvolverNode:

...
loadBuffer(ctx, "impulseResponseExample.wav", function(buffer){
  convolver.buffer = buffer;
  convolverGain.gain.value = 0.7;
  plainGain.gain.value = 0.3;
})
...
function loadBuffer(ctx, filename, callback) {
  var request = new XMLHttpRequest();
  request.open("GET", soundFileName, true);
  request.responseType = "arraybuffer";
  request.onload = function() {
    // Create a buffer and keep the channels unchanged.
    ctx.decodeAudioData(request.response, callback, function() {
      alert("Decoding the audio buffer failed");
    });
  };
  request.send();
}

Bringing It Together

Complete 3D audio means the context listener tracks the camera's position, orientation, and velocity, while every AudioPannerNode tracks its corresponding object, with all values updated every frame. Alongside ConvolverNode environmental effects, the Web Audio API supports convincing 3D soundscapes in WebGL scenes—everything from small rooms to spacious halls.