API

Getting Started - Chapter 2 - Sound

Adding Sound

Adding sounds to your world is very easy.

First, create an audio engine and unlock it. Note that we're using await to wait for the promises to resolve, so this needs to be done in an async function, for example:

import { CreateAudioEngineAsync } from "@babylonjs/core/AudioV2/webAudio/webAudioEngine";
async function initAudio() {
const audioEngine = await CreateAudioEngineAsync();
await audioEngine.unlockAsync();
// Audio engine is ready to play sounds ...
}

For continuously looping background music we use a streaming sound:

import { CreateStreamingSoundAsync } from "@babylonjs/core/AudioV2/abstractAudio/audioEngineV2";
CreateStreamingSoundAsync("name", "<sound file URL>", { loop: true, autoplay: true }, audioEngine);
Adding Sound To Your Scene

To play a short sound once we can use a sound that plays from a fully downloaded buffer:

import { CreateSoundAsync } from "@babylonjs/core/AudioV2/abstractAudio/audioEngineV2";
const sound = await CreateSoundAsync("sound", "<sound file URL>");
sound.play();

In the example below, setInterval is used to play the sound every 3 seconds.

Playing Sound Every 3 Seconds

Since you probably prefer listening to your own music as you work, and repeated sounds can get annoying, the above playground examples are the only ones in this tutorial that load sounds.

Now back to making our world and developing our buildings. Buildings come in varied sizes, positions, and orientations, and that will be true for the world we are creating.