The concept
Spatial audio simulates the direction and distance of a sound source. The Web Audio API provides PannerNode (azimuth, elevation, distance) and AudioListener (listener position). Moving the source in 3D space creates realistic spatialization — essential for XR and immersive installations.
The code
// Spatial audio: panning follows position
// Web Audio API PannerNode example
let ctx, panner, osc;
function setup() {
createCanvas(400, 280);
let btn = createButton('Start audio');
btn.position(10, 10);
btn.mousePressed(() => {
ctx = new (window.AudioContext || window.webkitAudioContext)();
osc = ctx.createOscillator();
panner = ctx.createPanner();
panner.panningModel = 'HRTF';
panner.distanceModel = 'inverse';
osc.connect(panner);
panner.connect(ctx.destination);
osc.frequency.value = 440;
osc.start();
btn.remove();
});
}
function draw() {
background(11, 15, 20);
if (panner) {
let x = map(mouseX, 0, width, -5, 5);
let z = map(mouseY, 0, height, -5, 5);
panner.positionX.value = x;
panner.positionZ.value = z;
}
fill(55,227,195); noStroke();
ellipse(mouseX, mouseY, 14, 14);
fill(255,255,255,50);
text('Move → hear panning', 20, height-20);
}Going further
Explore other free courses on the Workshops page.
Practice, collaborate, deploy — in 15 min.
Book a discovery call →