Load External Audio in Three.js Using AudioLoader
This article provides a step-by-step guide on how to correctly load
and play external audio files in a Three.js scene using the
AudioLoader class. You will learn how to set up an audio
listener, instantiate the loader, configure spatial or global audio, and
handle modern browser autoplay restrictions to ensure your sound plays
flawlessly.
To load and play audio in Three.js, you must follow a three-part
process: set up an AudioListener on your camera, initialize
a non-positional or positional audio object, and use the
AudioLoader to load the external file.
Step 1: Create an AudioListener
Before loading any audio, you need to define how the sound is heard.
The AudioListener represents the virtual ears of the user
and is typically attached to the active camera.
import * as THREE from 'three';
// Create a camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// Create an AudioListener and add it to the camera
const listener = new THREE.AudioListener();
camera.add(listener);Step 2: Initialize the Audio Object
Next, create an audio source container. You can choose between: * THREE.Audio: For ambient, background, or non-spatialized sounds. * THREE.PositionalAudio: For 3D spatialized sounds that get louder as the camera moves closer to an object.
// Create a global audio source
const sound = new THREE.Audio(listener);Step 3: Load the Audio File with AudioLoader
Instantiate the AudioLoader and use its
.load() method. This method takes the URL of your external
audio file (supporting standard web formats like MP3, OGG, and WAV) and
handles the asynchronous loading process through callbacks.
// Instantiate the AudioLoader
const audioLoader = new THREE.AudioLoader();
// Load the external audio file
audioLoader.load(
'path/to/your/audiofile.mp3', // Path to your external audio file
function(buffer) {
sound.setBuffer(buffer);
sound.setLoop(true);
sound.setVolume(0.5);
// Playback will begin here
},
function(xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded'); // Progress callback
},
function(err) {
console.error('An error occurred while loading the audio:', err); // Error callback
}
);Step 4: Handle Browser Autoplay Policies
Modern web browsers block audio from playing automatically before a
user interacts with the page. If you attempt to call
sound.play() inside the loading callback, the browser may
mute the audio or throw a console warning.
To resolve this, trigger the audio playback inside a user-initiated event listener, such as a click or button press.
// Function to start audio upon user interaction
function startAudio() {
if (listener.context.state === 'suspended') {
listener.context.resume(); // Resume the Web Audio Context
}
sound.play();
window.removeEventListener('click', startAudio); // Remove listener after activation
}
// Add event listener to the window
window.addEventListener('click', startAudio);