Note: We’re working on an improved sound controller that will allow for multiple tracks and positional sound. This feature will be unveiled soon.
Sound is a great way to provide feedback to user actions and events, background sounds can also give your scene more context and improve the user’s immersion into it.
Note: Keep in mind that the sounds of your scene will be heard by users that are in hearing range but outside your scene. Please be considerate with neighboring scenes when setting volumes and volume curves.
Supported sound formats vary depending on the browser, but it’s safe to use .mp3, .accc and .ogg.
.wav files are also supported but not generally recommended as they are significantly larger.
To play a sound, you need the following:
Entityto use for the sound location.
AudioSourcecomponent, added to that entity.
AudioClipobject, referenced by that component.
// Create entity const cube = new Entity() // Create AudioClip object, holding audio file const clip = new AudioClip('sounds/carnivalrides.ogg') // Create AudioSource component, referencing `clip` const source = new AudioSource(clip) // Add AudioSource component to entity cube.add(source) // Play sound source.playing = true
When creating an
AudioClip object, you need to provide the path to the location of the sound file.
The sound file must be inside the project folder. In the example above, the audio file is located in a
sounds folder, which is located at root level of the scene project folder.
Tip: We recommend keeping your sound files separate in a
/soundsfolder inside your scene.
Each entity can only have a single
AudioSource component, that can only have a single
AudioClip. This limitation can be easily overcome by including multiple invisible entities, each with their own sound.
Pausing stopping and looping
If you set the
playing property of an
AudioSource component to false, the file is paused. This means that if you later set
playing to true again, the sound file will continue from where it was paused.
You can use the
playOnce() function to play a sound once from start to finish, even if the sound was previously paused half way through.
To keep a sound playing in a continuous loop, set the
loop field of the
AudioSource component to true.
source.play = true source.loop = true
Looping sounds is especially useful for adding background music or other background sounds.
You can set the
volume property of the
AudioSource component to change the volume of a sound.
The volume can be a number from 0 to 1.
source.volume = 0.5
Note: Of course, the volume of a sound is also affected by the distance from the audio source.
Reuse sound objects
A great way to save processing power is to use a same
AudioClip object on many
Suppose you have a large amount of balls bouncing around in your scene, and you want to hear a thump sound every time two of them collide. You can add an
AudioSource component to each ball, and use a single
AudioClip object on all of these.