Spatial audio
Updated
Spatial audio makes a sound come from somewhere. A fountain in the square is loud when you stand next to it, quieter across the street, and on headphones you can tell it is on your left. This page covers the Positional Audio source, the three distance models that decide how fast a sound fades, and Audio Zones, boxes that stop the music of one room from leaking into the next.
Before you start
Section titled “Before you start”- Read Audio sources first. Positional Audio has every prop, method and event of the Audio component, plus the distance props on this page.
- Zone events reach scripts through a Signal Emitter on the zone entity. See Scripting for
onandEventType.
The listener
Section titled “The listener”The listener is where the scene hears from. It rides the active camera, and in a headset it follows the user’s head, so what you hear always matches what you see. Positional sounds are panned with a model of how human ears receive sound from each direction (an HRTF), so on headphones a sound can come from the left, the right, in front or behind. In a headset each source turns with the head exactly as on a desktop.
Positional Audio
Section titled “Positional Audio”The Positional Audio component (PositionalAudioComponent, comp-audio-positional) on a Positional Audio entity (PositionalAudioEntity) plays a sound file from its entity’s position. Move, parent or animate the entity and the sound moves with it: put a Positional Audio entity under a car and the engine noise follows the car.
| Prop | Type | Default | Description |
|---|---|---|---|
src |
string | none | The sound file: a URL or an asset of the project. |
volume |
number | 1 |
Gain, from 0 to 1. |
repeat |
'once' or 'repeat' |
'repeat' |
Play once, or loop. |
autoplay |
boolean | true |
Play once loaded, when the scene is active. Play mode only. |
refDistance |
number | 1 |
Distance in metres within which the sound is at full volume. |
rolloffFactor |
number | 1 |
How fast the volume falls past refDistance. Higher is faster. |
maxDistance |
number | 10000 |
For the linear model, the distance in metres where the sound reaches silence. The other models ignore it. |
distanceModel |
'inverse', 'linear' or 'exponential' |
'inverse' |
The curve the volume follows with distance. |
It has the same methods as Audio: play(), pause(), stop(), setVolume(v), isPlaying() and load(). It sends the same events as Audio under its own name: AudioPositional::ready, ::error, ::play, ::pause, ::stop and ::end, which scripts compare with EventType.AudioPositional.Ready and so on.
For the linear model, refDistance must be smaller than maxDistance.
Distance models
Section titled “Distance models”Within refDistance every model plays at full volume. Past it, for a listener at distance d, with ref = refDistance, max = maxDistance and r = rolloffFactor:
| Model | Volume past refDistance |
Character | Use it for |
|---|---|---|---|
inverse |
ref / |
A natural falloff that never quite reaches silence. | Most sounds. It is the default. |
linear |
1 − r × (d − ref) /, never below 0 |
Falls in a straight line to silence at maxDistance. |
Sounds that must stop at a known range. |
exponential |
(d / |
Falls faster than inverse as r grows. |
Sounds that should stay very local. |
Raise refDistance for loud, large sources such as a waterfall or a stage; lower it for small ones such as a ticking clock.
In the editor, a selected positional source shows a faint sphere at its refDistance.
Audio Zone
Section titled “Audio Zone”An Audio Zone (AudioZoneEntity, with the component AudioZoneComponent, comp-audio-zone) is an invisible box that decides which positional sounds the listener hears. While the listener is inside one or more zones, it hears only the positional sources inside the same zones. Every other positional source is muted. With the listener outside every zone, or no zones in the scene, every source plays normally.
For each positional source, the rules are:
- A source inside a zone the listener is also in is heard.
- A source inside zones the listener is not in is muted: zone audio is silent from outside.
- A source in no zone is heard only while the listener is outside every zone.
| Prop | Type | Default | Description |
|---|---|---|---|
halfExtents |
{ x, y, z } |
{ x: 1, y: 1, z: 1 } |
Half the box’s size along each axis, in metres, in the entity’s local space. The default is a 2 × 2 × 2 m cube. The entity’s Transform moves, rotates and scales the box. |
- Zones affect only Positional Audio and Positional Audio Tone sources. Global Audio, Audio Tone and Ambisonic sources are never muted by a zone, which makes them right for music that should play everywhere.
- A source with an Audio Fade crossfades over the fade’s
durationwhen a zone mutes or unmutes it. Without a Fade, it cuts. - A zone mute is separate from
volumeand from hiding: neither changes, and the source keeps playing silently. - Zones work in play only. In the editor a zone draws as a translucent violet box when gizmos are on.
Events
Section titled “Events”The listener crossing the zone’s box is reported to the Signal Emitters on the zone entity:
| Event | EventType constant |
Data | Sent when |
|---|---|---|---|
Audio |
Event |
{} |
The listener enters the zone. |
Audio |
Event |
{} |
The listener leaves it. |
Examples
Section titled “Examples”1. A radio you switch on
Section titled “1. A radio you switch on”A positional radio that starts and stops when the player clicks it. While it plays, it drives away and back, so you hear the music fade to silence with distance and return.
#pragma lifecycle(startup)
let sound;let trip;
function startup() { const radio = findEntity('Radio'); sound = findEntity('Radio Sound').getComponent(PositionalAudioComponent);
// 10 m away and back, for ever: paused until the music plays. trip = Tween.to(radio.position, { z: radio.position.z - 10 }, { duration: 5, ease: Ease.InOutSine, repeat: Infinity, yoyo: true, }); trip.pause();
on('radio/clicked', (event) => { if (event.eventType !== EventType.Selectable.Select) return; findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again if (sound.isPlaying()) { sound.pause(); trip.pause(); } else { sound.play(); trip.resume(); } });}Click a radio to switch its music on and off; while it plays, it drives 10 m away and back, and the music fades to silence and returns: a Positional Audio with a linear fade under a Selectable mesh, played and paused with its trip by a Behavior script.
With your sound on, click the radio: the music fades to silence as it drives away and comes back as it returns. Click it again to stop both.
How it works:
- The sound entity is a child of the radio mesh, so it always plays from where the radio is, even if the radio is moved.
refDistance: 1.5keeps the radio at full volume within 1.5 m. Thelinearmodel then fades it in a straight line to silence atmaxDistance, 12 m, so the fade is easy to hear.- Pausing keeps the position, so the song continues where it stopped.
- The trip is one endless tween whose handle is paused and resumed with the music, so the radio only travels while it plays. It starts about 2 m from you and drives past 12 m, so the music fades to silence and comes back.
2. Impact sounds where things collide
Section titled “2. Impact sounds where things collide”Move one positional sound to each collision point and play it.
#pragma lifecycle(startup)
// Scene: crates with Rigid Bodies, colliders and a Signal Emitter on 'crate/hit'.// At the scene root, a Positional Audio entity "Thud" (src: a thud, repeat: once, autoplay: off).let thud;let thudSound;
function startup() { thud = findEntity('Thud'); thudSound = thud.getComponent(PositionalAudioComponent);
on('crate/hit', (event) => { if (event.eventType !== EventType.PhysicsCollider.CollisionEnter) return; const point = event.data.contact; if (!point) return; thud.position.set(point.x, point.y, point.z); thudSound.stop(); thudSound.play(); });}Each collision of a crate moves one Positional Audio thud to the contact point and plays it there, so you hear where the crate landed.
Click once to let the browser start the sound. Then grab a crate, lift it and drop it to hear it land where it falls. Drag elsewhere to orbit the camera.
How it works:
PhysicsCollider::collision-entercarriescontact, the world point where the bodies touched. BecauseThudsits at the scene root, its local position is a world position.- Moving the entity moves the sound: the thud comes from where the crates met.
stop()thenplay()restarts the one-shot. One sound entity serves every crate; when two collisions come in the same instant, the second one wins. For overlapping impacts, see the next example.
3. Show which room you are in
Section titled “3. Show which room you are in”Use zone events to update a label and change the music.
#pragma lifecycle(startup)
const ROOM_NAMES = { 'Library Zone': 'Library', 'Workshop Zone': 'Workshop',};let label;let hallMusic;let inside = 0;
function startup() { label = findEntity('Room Name').getComponent(UILabelComponent); hallMusic = findEntity('Hall Music').getComponent(AudioComponent);
on('room', (event) => { const zone = findEntity(event.entityId); if (event.eventType === EventType.AudioZone.Enter) { inside += 1; label.setProps({ text: ROOM_NAMES[zone.name] ?? zone.name }); hallMusic.setVolume(0.15); } if (event.eventType === EventType.AudioZone.Exit) { inside -= 1; if (inside === 0) { label.setProps({ text: 'Main hall' }); hallMusic.setVolume(0.6); } } });}Two Audio Zones, a library with rain on its windows and a workshop with a drum loop: their enter and exit events name the room in a HUD label and lower the hall music.
With your sound on, hold A for half a second to walk into the library, or D to walk into the workshop. Inside a room you hear only its own sound, and the label names it. The rain and the beat are short loops generated for this example.
How it works:
- All zones share one signal;
event.entityIdtells which zone sent the event, andfindEntity(id)turns the id into the entity, whosenamepicks the room title. - Global Audio is never muted by zones, so the hall music keeps playing everywhere. The script lowers it inside a room instead, so the room’s own positional sounds stand out.
insidecounts the zones the listener is in, because zones can overlap: the hall settings come back only when the listener has left them all.
Snippets
Section titled “Snippets”1. Overlapping one-shots with spawned copies
Section titled “1. Overlapping one-shots with spawned copies”Spawn a copy of a template sound at each footstep and remove it when it ends, so several can play at once.
#pragma lifecycle(startup)
// Scene: a disabled Positional Audio entity "Step Template"// (src: a footstep, repeat: once, autoplay: on) with a Signal Emitter on 'step'.// A character script emits 'player/step' with { x, y, z } on each footstep.function startup() { on('player/step', (where) => { spawn('Step Template', { position: where, enabled: true }); });
// Each copy reports its own end; remove that copy. on('step', (event) => { if (event.eventType === EventType.AudioPositional.End || event.eventType === EventType.AudioPositional.Error) { destroy(event.entityId); } });}How it works:
spawn(name, options)copies the template entity with its components, places it atpositionand enables it. Because the template’s source hasautoplayon, the copy plays as soon as it is active.- The copy keeps the template’s Signal Emitter, so every copy reports on
step.event.entityIdidentifies which copy finished. destroy(event.entityId)removes that copy and frees it. Removing onErrortoo keeps broken copies from piling up.- The template stays disabled, so it never plays itself.
2. A siren whose reach grows
Section titled “2. A siren whose reach grows”Change distance props at runtime to make an alarm carry further, with a hard edge.
#pragma lifecycle(startup)
// Scene: a Positional Audio entity "Siren" (src: a siren loop, autoplay: off,// distanceModel: linear, refDistance: 2, maxDistance: 10).// Something emits 'alarm/level' with 0 (off), 1, 2 or 3.let siren;
function startup() { siren = findEntity('Siren').getComponent(PositionalAudioComponent);
on('alarm/level', (level) => { if (level === 0) { siren.stop(); return; } // Level 1 reaches 10 m, level 2 reaches 25 m, level 3 reaches 60 m. const reach = [0, 10, 25, 60][level]; siren.setProps({ distanceModel: 'linear', refDistance: 2, maxDistance: reach }); if (!siren.isPlaying()) siren.play(); });}How it works:
- With the
linearmodel the siren is at full volume within 2 m and silent exactly atmaxDistance, so each level has a precise radius. setPropschanges the distance props on the sound that is already playing; there is no need to restart it.refDistancestays below everymaxDistance, as thelinearmodel requires.
Common mistakes
Section titled “Common mistakes”- Using global Audio for a sound that should come from an object. Global sources do not pan or fade with distance. Use Positional Audio.
- Setting
maxDistancewith theinversemodel. It has no effect. Switch tolinearfor a hard edge, or use an Audio Zone. - Expecting zones to mute music. Zones never affect global Audio, Audio Tone or Ambisonic sources. Lower their volume from a script on
AudioZone::enterif needed. - Forgetting the Signal Emitter on the zone. Zone events go to the zone entity’s own Signal Emitters.
- Listening for
Audio::endon a positional source. Positional sources sendAudioPositional::…events. - Placing a one-shot by world position under a moved parent.
entity.positionis relative to the parent. Keep entities you place at world points at the scene root, or convert the point to the parent’s space. - Expecting zones in the editor. Zones act in play only.