How to Use Three.js PositionalAudio for 3D Sound

Creating immersive web experiences often requires spatial audio that changes based on the user’s camera position and orientation. This article provides a quick, step-by-step guide on how to set up an AudioListener, create a PositionalAudio object, load an audio asset, and attach it directly to a 3D mesh in Three.js to simulate realistic 3D sound.

Step 1: Create and Add an AudioListener to the Camera

To experience spatial audio, your Three.js scene needs “ears.” This is handled by the AudioListener object, which must be added to the active camera so the engine can calculate how sound propagates relative to the viewer’s viewpoint.

// Initialize the listener
const listener = new THREE.AudioListener();

// Add the listener to the camera
camera.add(listener);

Step 2: Initialize the PositionalAudio Object

Once the listener is attached to the camera, you can create the PositionalAudio object. This object acts as the sound source in your 3D space.

const sound = new THREE.PositionalAudio(listener);

Step 3: Load the Audio File

Use the AudioLoader class to load an audio file (such as an .mp3, .ogg, or .wav). Once the file is loaded, assign the audio buffer to your PositionalAudio object.

const audioLoader = new THREE.AudioLoader();

audioLoader.load('path/to/sound.mp3', function(buffer) {
    sound.setBuffer(buffer);
    sound.setRefDistance(20); // Distance at which the volume starts to reduce
    sound.setRolloffFactor(2); // How quickly the volume fades as the camera moves away
    sound.setLoop(true);       // Loop the audio
    sound.setVolume(0.5);      // Set volume (0.0 to 1.0)
    sound.play();              // Start playing the sound
});

Step 4: Attach the Audio Object to a Mesh

To bind the source of the sound to a physical object in your scene, simply add the PositionalAudio object as a child of your mesh. Because PositionalAudio inherits from Object3D, it will automatically track the mesh’s position and orientation.

// Create a 3D mesh
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const mesh = new THREE.Mesh(geometry, material);

// Add the mesh to the scene
scene.add(mesh);

// Attach the spatial sound to the mesh
mesh.add(sound);

Fine-Tuning the 3D Audio Experience

To make the sound simulation more realistic, you can configure how the sound behaves using the following methods: