Skip to content

Audio sources

Updated

An audio source is the component that makes an audio entity’s sound. This page covers the two sources that play sound files without placing them in space, Audio and Audio Ambisonic, and the two optional components every source can take: Audio Fade, which ramps a sound in and out, and Audio Analyzer, which turns a sound into numbers your script can use to animate things. It also explains how hiding and disabling silence a source, and why browsers wait for the first click before they make any sound.

  • You should know how a Behavior script finds an entity and its components: findEntity(name) and entity.getComponent(Class). See Working with entities.
  • Source events reach scripts through a Signal Emitter on the audio entity. See Scripting for on, emit and EventType.
  • For sounds placed in the world, read Spatial audio after this page. For synthesized notes, read Tones.

An audio entity plays exactly one sound. Each kind of entity carries one source component, which it requires:

Entity Class Source component Plays
Audio (ent-audio) AudioEntity AudioComponent (comp-audio) A sound file heard the same everywhere: music, ambience, narration, UI sounds.
Positional Audio (ent-audio-positional) PositionalAudioEntity PositionalAudioComponent A sound file placed in the world. See Spatial audio.
Audio Ambisonic (ent-audio-ambisonic) AmbisonicAudioEntity AudioAmbisonicComponent (comp-audio-ambisonic) A 360-degree soundfield that turns with the listener’s head.
Audio Tone (ent-audio-tone) AudioToneEntity AudioToneComponent A synthesizer heard everywhere. See Tones.
Positional Audio Tone (ent-audio-tone-positional) PositionalAudioToneEntity PositionalAudioToneComponent A synthesizer placed in the world. See Tones.
  • One source per entity. The required source cannot be removed; you control it through its props and its methods. Disabling it stops and releases its sound, like any other component, until it is enabled again. Adding a second source component to an audio entity throws an error. For two sounds, use two entities.
  • A Transform. Every audio entity has a Transform. It places positional sources; for global ones it only places the editor icon.
  • Nothing drawn. An audio entity draws nothing in play. In the editor it shows a loudspeaker icon.

These optional components extend an audio entity:

Component Audio Positional Audio Ambisonic Tones
Audio Fade yes yes yes yes
Audio Analyzer yes yes no yes
Audio filters yes yes yes yes

The Audio component (AudioComponent, comp-audio) loads a sound file and plays it, heard the same wherever the listener is. Use it for music, ambience beds, narration and interface sounds.

Prop Type Default Description
src string none The sound file: a URL or an asset of the project.
volume number 1 Gain, from 0 (silent) to 1 (full).
repeat 'once' or 'repeat' 'repeat' 'once' plays to the end and stops; 'repeat' starts again from the beginning.
autoplay boolean true Play as soon as the sound has loaded and the scene is active. Applies in play only.

Change props from a script with setProps. Changing src loads the new file; volume and repeat apply to the sound already playing.

music.setProps({ repeat: 'once', volume: 0.6 });
Method What it does
play() Start playing, or resume after a pause(). Does nothing until the sound has loaded.
pause() Pause and keep the position. The next play() resumes there.
stop() Stop. The next play() starts from the beginning.
setVolume(v) Set the gain at once, from 0 to 1. Values outside that range are clamped.
isPlaying() true while the sound is playing.
load() A promise that resolves once the sound has loaded. Await it before playing a file you just changed.
  • Loading. A scene waits for its sounds while it loads, so an autoplaying sound is ready when the scene appears.
  • Entering the scene plays every source with autoplay on.
  • Leaving the scene stops each source, or fades it out first when it has an Audio Fade.
  • In the editor nothing autoplays. Selecting an audio entity plays it so you can audition it; deselecting it stops it.

A source sends its events to the Signal Emitters on its own entity. Add one with a signal, then listen to that signal with on. The Audio component sends Audio::… events, Positional Audio sends AudioPositional::…, and Audio Ambisonic sends AudioAmbisonic::….

Event EventType constant Data Sent when
Audio::ready EventType.Audio.Ready { duration }, in seconds The sound has loaded.
Audio::error EventType.Audio.Error { message } The sound cannot load.
Audio::play EventType.Audio.Play {} It starts playing.
Audio::pause EventType.Audio.Pause {} A playing sound is paused.
Audio::stop EventType.Audio.Stop {} A playing sound is stopped, by a script or by leaving the scene.
Audio::end EventType.Audio.End {} A sound set to play 'once' reaches its end by itself.

Every event arrives in the shape { entityId, eventType, data }. entityId tells you which entity sent it, which matters when several sources share one signal.

An ambisonic recording captures sound from every direction around one point, like a 360-degree photo for the ears. The Audio Ambisonic component (AudioAmbisonicComponent, comp-audio-ambisonic) plays such a file around the listener and turns it as the listener turns, so a forest stays where it is when the player looks around. Use it for rich ambience: a forest, a city street, a stadium.

Prop Type Default Description
src string none An ambisonic B-format file with 4, 9 or 16 channels.
order number Auto Ambisonic order: 1, 2 or 3. Left unset, it is inferred from the number of channels in the file.
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.

It has the same methods as Audio: play(), pause(), stop(), setVolume(v), isPlaying() and load(). It sends the same events, named AudioAmbisonic::ready, ::error, ::play, ::pause, ::stop and ::end (EventType.AudioAmbisonic.Play and so on). Higher orders sound more precise and cost more processing, which matters on standalone headsets.

Browsers keep a page silent until the user interacts with it. MIRA listens for the first click, tap, touch or key press and unlocks audio then. Sources that autoplayed before that moment start sounding at once; nothing needs to be played again. Notes a tone plays before the gesture are scheduled and sound once audio unlocks. If the browser suspends audio later, for example during a phone call or in a background tab, the next gesture unlocks it again.

Two different things silence a source, and they behave differently:

Hidden Disabled
How entity.visible = false on the audio entity or any entity above it. entity.setEnabled(false) on the audio entity or any entity above it.
Playback Keeps playing silently, and is heard again in place when shown. Stops.
Coming back visible = true: heard again at its current position. setEnabled(true): plays from the start when autoplay is on.
Volume, fade, zones, events Untouched. With an Audio Fade, it fades out before stopping.
Lasts For the session only: visibility is never saved. Like any entity’s enabled state.

The mute while hidden comes after the source’s volume, so it never fights a fade or a zone, and an echo or reverb on the source rings out naturally.

The Audio Fade component (AudioFadeComponent, comp-audio-fade) ramps its entity’s source in and out as the entity becomes active and inactive: when the scene is entered and left, and when the entity is enabled and disabled. Use it so music never starts or stops abruptly.

Prop Type Default Description
mode 'fade-in', 'fade-out' or 'fade-in-out' 'fade-in-out' Fade in when the source becomes active, fade out when it becomes inactive, or both.
duration number 0.4 Fade length in seconds, from 0 to 10. 0 switches instantly.
  • When the player switches scenes, an outgoing source with a fade-out keeps playing until its fade ends, even after the next scene is active.
  • An audio zone crossfades a source that has a Fade over the Fade’s duration instead of cutting it.
  • A script’s play() and stop() are not faded: stop() cuts at once. To fade from a script, disable the entity (the Fade handles it) or animate the volume yourself, as in the examples.

The Audio Analyzer component (AudioAnalyzerComponent, comp-audio-analyzer) measures how loud each frequency of its entity’s sound is, right now. A frequency bin is one slice of the spectrum, from the lowest bass at index 0 to the highest treble at the end. Use it for equalizer bars, speakers that throb to the beat or lights that pulse with music. It works on Audio, Positional Audio and both tone entities.

Prop Type Default Description
fftSize number 2048 Size of the analysis window, in samples: a power of two from 32 to 32768. The data has fftSize / 2 bins. Larger values give finer bins and cost more.
Method Returns
getFrequencyData() A Uint8Array with one value from 0 to 255 per bin, or undefined while the source has nothing to play. The same array is reused on every call.
getAverageFrequency() The average of all bins, from 0 to 255; 0 while the source has nothing to play.

The analyzer samples only when you call it, so it costs nothing until a script asks. Reading it once per frame in update is the intended use.

A short sound replayed every time the player presses a UI button.

ClickSound.jx
#pragma lifecycle(startup)
let click;
function startup() {
click = findEntity('Click').getComponent(AudioComponent);
on('ui/press', (event) => {
if (event.eventType !== EventType.UIButton.Press) return;
click.stop(); // rewind, in case the last click is still playing
click.play();
});
}

How it works:

  • The Audio entity is authored with repeat: 'once' and autoplay off, so it is silent until a script plays it.
  • stop() before play() rewinds the sound. Without it, a press during a playing click would do nothing, because play() on a playing sound changes nothing.
  • One signal serves every button: each button’s Signal Emitter uses the same ui/press signal.

Lower the music smoothly while a voice-over plays, then bring it back.

Ducking.jx
#pragma lifecycle(startup)
// Scene: an Audio entity "Music" (autoplay, repeat) and an Audio entity "Narrator"
// (repeat: once, autoplay: off) with a Signal Emitter on 'narrator'.
// Something emits 'story/next' to start the narration.
const NORMAL = 0.8;
const DUCKED = 0.2;
let music;
let narrator;
let level = NORMAL;
let ramp;
function fadeMusicTo(target) {
if (ramp) ramp.stop();
ramp = Tween.value(level, target, (value) => {
level = value;
music.setVolume(value);
}, { duration: 0.6 });
}
function startup() {
music = findEntity('Music').getComponent(AudioComponent);
narrator = findEntity('Narrator').getComponent(AudioComponent);
music.setVolume(level);
on('story/next', () => narrator.play());
on('narrator', (event) => {
if (event.eventType === EventType.Audio.Play) fadeMusicTo(DUCKED);
if (event.eventType === EventType.Audio.End || event.eventType === EventType.Audio.Stop) fadeMusicTo(NORMAL);
});
}

How it works:

  • Tween.value(from, to, onValue, options) calls onValue every frame with a number moving from from to to over duration seconds. Each value goes to setVolume, which applies it at once.
  • level remembers the current volume, so a new fade always starts from where the last one is, even halfway.
  • ramp.stop() cancels a fade still running before starting the next one, so two fades never fight.
  • The narrator’s own events drive the ducking: Play lowers the music, End (it finished) or Stop (it was cut) raises it again.

Play several tracks one after another, and skip with a key.

Playlist.jx
#pragma lifecycle(startup, update)
// Scene: an Audio entity "Jukebox" (repeat: once, autoplay: off)
// with a Signal Emitter on the signal 'jukebox'.
const TRACKS = [
'/example-assets/ambient.mp3',
'/example-assets/beat-loop.wav',
'/example-assets/rain-loop.wav',
];
let jukebox;
let index = 0;
let switching = false;
async function playTrack(i) {
switching = true;
index = (i + TRACKS.length) % TRACKS.length;
jukebox.stop();
jukebox.setProps({ src: TRACKS[index] });
await jukebox.load();
jukebox.play();
switching = false;
log(`Now playing track ${index + 1} of ${TRACKS.length}`);
}
function startup() {
jukebox = findEntity('Jukebox').getComponent(AudioComponent);
on('jukebox', (event) => {
if (event.eventType === EventType.Audio.End) playTrack(index + 1);
if (event.eventType === EventType.Audio.Error) {
log('Skipping a track that cannot load:', event.data.message);
playTrack(index + 1);
}
});
playTrack(0);
}
function update() {
if (switching) return;
if (Input.keyboard.isKeyReleased(Key.N)) playTrack(index + 1);
if (Input.keyboard.isKeyReleased(Key.P)) playTrack(index - 1);
}

How it works:

  • The source plays 'once', so it sends Audio::end when a track finishes, which starts the next one.
  • setProps({ src }) loads a new file; await jukebox.load() waits until it has loaded, because play() does nothing before that.
  • playTrack is an async function, so it may use await. startup and update call it without waiting for it.
  • The switching flag ignores key presses while a track is loading, and (i + TRACKS.length) % TRACKS.length wraps the index in both directions.
  • Audio::error skips a broken file instead of leaving the jukebox silent. A playlist whose every file fails would loop; a real project would count failures and give up.

Read the analyzer each frame and scale an object with the low frequencies.

BassPulse.jx
#pragma lifecycle(startup, update)
let analyzer;
let cone;
let smoothed = 0;
function startup() {
analyzer = findEntity('Beat').getComponent(AudioAnalyzerComponent);
cone = findEntity('Speaker Cone');
}
function update(dt) {
const bins = analyzer.getFrequencyData();
if (!bins) return; // nothing playing yet
// The first few bins hold the bass.
const bass = (bins[0] + bins[1] + bins[2] + bins[3]) / (4 * 255);
// Rise fast, fall slowly, so the pulse reads as a beat.
smoothed = bass > smoothed ? bass : Math.max(0, smoothed - dt * 2);
cone.scale.setScalar(1 + smoothed * 0.4);
}

How it works:

  • With fftSize: 256 there are 128 bins; the lowest ones hold the bass. Values go from 0 to 255, so dividing by 255 gives 0 to 1.
  • getFrequencyData() returns undefined until the source plays: the early return skips those frames.
  • The smoothing lets the cone jump with each beat and settle gently, which looks better than following every raw value.
  • cone.scale.setScalar(...) sets the scale on all three axes at once.

Drive a row of bars from the whole spectrum.

Equalizer.jx
#pragma lifecycle(startup, update)
// Scene: an Audio entity "Music" with an Audio Analyzer (fftSize: 512),
// and eight thin box meshes named "Bar 1" … "Bar 8" standing in a row.
const BAR_COUNT = 8;
let analyzer;
const bars = [];
function startup() {
analyzer = findEntity('Music').getComponent(AudioAnalyzerComponent);
for (let i = 1; i <= BAR_COUNT; i++) bars.push(findEntity(`Bar ${i}`));
}
function update() {
const bins = analyzer.getFrequencyData();
if (!bins) return;
// Split the lower half of the spectrum into equal bands, one per bar.
const usable = Math.floor(bins.length / 2);
const perBar = Math.floor(usable / BAR_COUNT);
for (let b = 0; b < BAR_COUNT; b++) {
let sum = 0;
for (let i = b * perBar; i < (b + 1) * perBar; i++) sum += bins[i];
const level = sum / (perBar * 255);
bars[b].scale.y = 0.1 + level * 3;
}
}

How it works:

  • The bars are looked up once in startup and kept in an array; findEntity by name is too slow to call every frame.
  • Most musical energy sits in the lower half of the spectrum, so the script spreads the bars over that half.
  • Each bar averages its band and maps it to a height. Scaling only y stretches the bar upward from its center.

6. A mute key that keeps the music in sync

Section titled “6. A mute key that keeps the music in sync”

Hide the source instead of pausing it, so it carries on silently and comes back in place.

MuteKey.jx
#pragma lifecycle(startup, update)
// Scene: an Audio entity "Music" (autoplay, repeat).
let music;
function startup() {
music = findEntity('Music');
}
function update() {
if (!Input.keyboard.isKeyReleased(Key.M)) return;
music.visible = !music.visible;
log(music.visible ? 'Sound on' : 'Sound off');
}

How it works:

  • Hiding an audio entity mutes it but keeps it playing, so when it is shown again the music is where it would have been, still in time with anything synchronized to it.
  • isKeyReleased(Key.M) is true for one frame per press, so one press toggles once.
  • Visibility is never saved, so the next session starts with sound on.

Use Audio Fade so switching an ambience on and off is always smooth, without any volume code.

Weather.jx
#pragma lifecycle(startup)
// Scene: two Audio entities, "Rain" and "Wind", each with an Audio Fade
// (mode: fade-in-out, duration: 2). "Rain" starts disabled.
// A weather system emits 'weather' with 'rain' or 'clear'.
let rain;
let wind;
function startup() {
rain = findEntity('Rain');
wind = findEntity('Wind');
on('weather', (kind) => {
const raining = kind === 'rain';
rain.setEnabled(raining); // fades in over 2 s when enabled
wind.setEnabled(!raining); // fades out over 2 s when disabled
});
}

How it works:

  • Enabling an entity activates its source, and the Audio Fade ramps it in over duration. Disabling it ramps it out before stopping.
  • A script’s emit('weather', 'rain') delivers 'rain' itself to the callback; component events, by contrast, arrive as { entityId, eventType, data }.
  • Because the sources are authored with autoplay, enabling them is enough to start them.
  • Calling play() before the sound has loaded. play() does nothing until the file is ready. After changing src, await source.load() first, or wait for Audio::ready.
  • Expecting events without a Signal Emitter. A source sends its events only to Signal Emitters on its own entity. No emitter, no events.
  • Comparing against the wrong event group. A Positional Audio source sends AudioPositional::…, not Audio::…. Compare with EventType.AudioPositional.End for those.
  • Replaying a one-shot with play() alone. On a sound that is still playing, play() changes nothing. Call stop() first to rewind.
  • Expecting stop() to fade. A script’s stop() and play() are never faded. Disable the entity to use its Audio Fade, or tween the volume.
  • Looking sources up every frame. Call findEntity and getComponent once in startup and keep the result.
  • Adding a second source to one entity. An audio entity holds one sound. Create another audio entity instead.
  • Assuming sound on load. Nothing is audible until the user’s first click, tap or key press.