Babylon.js Audio — 3D Spatial Sound System
In this tutorial, you will learn about Babylon.js Audio. We cover key concepts, practical examples, and best practices to help you master this topic.
Babylon.js audio engine provides 3D spatial sound with doppler effect, distance attenuation, and mesh-attached audio sources for immersive experiences.
What You'll Learn
By the end of this guide, you will load audio files as 3D sounds, attach sound to meshes, configure distance attenuation and rolloff, use spatial panning for directional audio, manage audio groups and volumes, and handle audio resource cleanup.
Basic 3D Sound
var sound = new BABYLON.Sound('engine', 'engine.wav', scene, null, {
loop: true,
autoplay: true,
spatialSound: true,
maxDistance: 20,
distanceModel: 'linear'
});
sound.attachToMesh(carMesh);
Sound with Position
var explosion = new BABYLON.Sound('explosion', 'explosion.wav', scene, function() {
explosion.play();
}, {
spatialSound: true,
position: new BABYLON.Vector3(5, 0, 3),
maxDistance: 15,
rolloffFactor: 1.5
});
Audio Groups
var sfxGroup = new BABYLON.SoundGroup('sfx');
var musicGroup = new BABYLON.SoundGroup('music');
var sound1 = new BABYLON.Sound('click', 'click.wav', scene, null, {
soundGroup: sfxGroup
});
// Control entire group
sfxGroup.setVolume(0.5);
musicGroup.setVolume(0.3);
Common Mistakes
1. Audio File Format
Use .mp3 for wide compatibility, .ogg for higher quality. Some browsers block autoplay.
2. Missing Spatial Configuration
Without spatialSound: true, sound plays in 2D (full volume regardless of distance).
3. Distance Model Not Set
Choose 'linear', 'exponential', or 'inverse' distance models. Default is linear.
4. Not Calling dispose
Audio buffers stay in memory. Dispose sounds when no longer needed: sound.dispose().
5. Browser Autoplay Policy
Browsers block autoplay. Play audio on user gesture first, then continue.
Practice Questions
Q1: How do you make a sound spatial (3D)? A: Set spatialSound: true in the Sound constructor options.
Q2: What does maxDistance control? A: The distance at which the sound becomes inaudible.
Q3: How do you attach sound to a moving mesh? A: Call sound.attachToMesh(mesh). Sound follows the mesh.
Q4: What distance models are available? A: 'linear', 'exponential', 'inverse'.
Q5: How do you create a sound group? A: Use new BABYLON.SoundGroup('name') and assign via soundGroup option.
Challenge: Build a scene where each object emits a unique 3D spatial sound. As the camera moves closer, the sound gets louder. Add a mute toggle button.
FAQ
Try It Yourself
Build a scene with spatial audio.
<!DOCTYPE html>
<html>
<head>
<title>Babylon.js Audio</title>
<script src="https://cdn.babylonjs.com/babylon.js"></script>
</head>
<body style="font-family:sans-serif;padding:20px;">
<h2>3D Audio Demo</h2>
<button onclick="playClick()">Play Click (2D)</button>
<canvas id="renderCanvas" style="width:100%;height:400px;border-radius:8px;"></canvas>
<script>
var canvas = document.getElementById('renderCanvas');
var engine = new BABYLON.Engine(canvas, true);
var scene = new BABYLON.Scene(engine);
var camera = new BABYLON.ArcRotateCamera('camera', -Math.PI/2, Math.PI/3, 10, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
new BABYLON.HemisphericLight('light', new BABYLON.Vector3(0, 1, 0), scene);
var sphere = BABYLON.MeshBuilder.CreateSphere('sphere', { diameter: 1 }, scene);
sphere.position.x = 3;
var mat = new BABYLON.StandardMaterial('mat', scene);
mat.diffuseColor = new BABYLON.Color3(0.3, 0.6, 1);
sphere.material = mat;
// Generate a simple beep sound using Web Audio API
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
function generateBeep(frequency, duration) {
var sampleRate = audioCtx.sampleRate;
var length = sampleRate * duration;
var buffer = audioCtx.createBuffer(1, length, sampleRate);
var data = buffer.getChannelData(0);
for (var i = 0; i < length; i++) {
data[i] = Math.sin(2 * Math.PI * frequency * i / sampleRate) * 0.5;
}
return buffer;
}
var beepBuffer = generateBeep(440, 0.2);
// Spatial click attached to sphere
var spatialSound = new BABYLON.Sound('spatial', null, scene, null, {
spatialSound: true,
maxDistance: 15,
distanceModel: 'linear',
sourceBuffer: beepBuffer
});
spatialSound.attachToMesh(sphere);
function playClick() {
spatialSound.play();
}
// 2D click sound
var clickSound = new BABYLON.Sound('click', null, scene, null, {
sourceBuffer: beepBuffer
});
// Also click on sphere click
sphere.actionManager = new BABYLON.ActionManager(scene);
sphere.actionManager.registerAction(new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnPickTrigger, function() {
spatialSound.play();
}));
engine.runRenderLoop(function() { scene.render(); });
window.addEventListener('resize', function() { engine.resize(); });
</script>
</body>
</html>
What's Next
Build UI with Babylon.js GUI.
GUI — GUI system. Optimization — Performance optimization.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro