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.
Before you start
Section titled “Before you start”- You should know how a Behavior script finds an entity and its components:
findEntity(name)andentity.getComponent(Class). See Working with entities. - Source events reach scripts through a Signal Emitter on the audio entity. See Scripting for
on,emitandEventType. - For sounds placed in the world, read Spatial audio after this page. For synthesized notes, read Tones.
Audio entities
Section titled “Audio entities”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 |
Audio (comp-audio) |
A sound file heard the same everywhere: music, ambience, narration, UI sounds. |
Positional Audio (ent-) |
Positional |
Positional |
A sound file placed in the world. See Spatial audio. |
Audio Ambisonic (ent-) |
Ambisonic |
Audio (comp-) |
A 360-degree soundfield that turns with the listener’s head. |
Audio Tone (ent-) |
Audio |
Audio |
A synthesizer heard everywhere. See Tones. |
Positional Audio Tone (ent-) |
Positional |
Positional |
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 });Methods
Section titled “Methods”| 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. |
Lifecycle
Section titled “Lifecycle”- 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
autoplayon. - 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.
Events
Section titled “Events”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 |
Event |
{ duration }, in seconds |
The sound has loaded. |
Audio::error |
Event |
{ message } |
The sound cannot load. |
Audio::play |
Event |
{} |
It starts playing. |
Audio::pause |
Event |
{} |
A playing sound is paused. |
Audio::stop |
Event |
{} |
A playing sound is stopped, by a script or by leaving the scene. |
Audio::end |
Event |
{} |
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.
Audio Ambisonic
Section titled “Audio Ambisonic”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.
Autoplay and the first gesture
Section titled “Autoplay and the first gesture”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.
Hiding and switching off
Section titled “Hiding and switching off”Two different things silence a source, and they behave differently:
| Hidden | Disabled | |
|---|---|---|
| How | entity. on the audio entity or any entity above it. |
entity. 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. |
set: 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.
Audio Fade
Section titled “Audio Fade”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.
Rain and wind ambiences with an Audio Fade each: a Behavior script only enables and disables the two Audio entities, and the fades cross over two seconds.
With your sound on, press Rain: the wind fades out as the rain fades in over two seconds. Press Clear to swap back. The rain is a short loop generated for this example. Drag outside the panel to orbit the camera.
| 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
durationinstead of cutting it. - A script’s
play()andstop()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.
Audio Analyzer
Section titled “Audio Analyzer”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 |
|---|---|
get |
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. |
get |
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.
Examples
Section titled “Examples”1. A click sound for any button
Section titled “1. A click sound for any button”A short sound replayed every time the player presses a UI button.
#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(); });}Every button of a menu plays the same short click, rewound on each press so fast presses all sound: one Audio entity with autoplay off, played by a Behavior script on a shared signal.
Press the buttons, quickly too. Drag to orbit the camera, scroll to zoom. The click is a tiny sound generated for this example.
How it works:
- The Audio entity is authored with
repeat: 'once'andautoplayoff, so it is silent until a script plays it. stop()beforeplay()rewinds the sound. Without it, a press during a playing click would do nothing, becauseplay()on a playing sound changes nothing.- One signal serves every button: each button’s Signal Emitter uses the same
ui/presssignal.
2. Duck the music during narration
Section titled “2. Duck the music during narration”Lower the music smoothly while a voice-over plays, then bring it back.
#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); });}While a narration track plays, a tween lowers the music to 0.2 of its volume, and brings it back to 0.8 when the narration ends or stops.
Click once to let the browser start the sound. Then press Narrate: the music dips while the narration (a rain recording here) plays, and comes back after it.
How it works:
Tween.value(from, to, onValue, options)callsonValueevery frame with a number moving fromfromtotooverdurationseconds. Each value goes tosetVolume, which applies it at once.levelremembers 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:
Playlowers the music,End(it finished) orStop(it was cut) raises it again.
3. A playlist
Section titled “3. A playlist”Play several tracks one after another, and skip with a key.
#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);}A jukebox plays three tracks one after another, moving on at the end event; N and P skip forward and back.
Click once to let the browser start the sound. Then press N for the next track and P for the previous one. Drag to orbit the camera, scroll to zoom.
How it works:
- The source plays
'once', so it sendsAudio::endwhen a track finishes, which starts the next one. setProps({ src })loads a new file;await jukebox.load()waits until it has loaded, becauseplay()does nothing before that.playTrackis anasyncfunction, so it may useawait.startupandupdatecall it without waiting for it.- The
switchingflag ignores key presses while a track is loading, and(i + TRACKS.length) % TRACKS.lengthwraps the index in both directions. Audio::errorskips 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.
4. A speaker that throbs to the bass
Section titled “4. A speaker that throbs to the bass”Read the analyzer each frame and scale an object with the low frequencies.
#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);}An Audio Analyzer on a looping beat: each frame a Behavior script averages the lowest frequency bins and scales the speaker cone with them.
Click once to let the browser start the sound, then watch the amber cone jump on every kick drum. The beat is a short loop generated for this example. Drag to orbit the camera, scroll to zoom.
How it works:
- With
fftSize: 256there are 128 bins; the lowest ones hold the bass. Values go from 0 to 255, so dividing by 255 gives 0 to 1. getFrequencyData()returnsundefineduntil the source plays: the earlyreturnskips 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.
5. An equalizer made of bars
Section titled “5. An equalizer made of bars”Drive a row of bars from the whole spectrum.
#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; }}Every frame a script reads an Audio Analyzer's frequency data, splits the lower half into eight bands and scales a bar to each band's level.
Click once to let the browser start the sound. Then watch the bars jump with the beat. Drag to orbit the camera, scroll to zoom.
How it works:
- The bars are looked up once in
startupand kept in an array;findEntityby 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
ystretches 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.
#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');}M hides and shows the music entity: hidden, it keeps playing silently, so it comes back in place instead of from the start.
Click once to let the browser start the sound. Then press M to mute the music and M again to bring it back where it would be.
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.
Snippets
Section titled “Snippets”1. Weather that fades in and out
Section titled “1. Weather that fades in and out”Use Audio Fade so switching an ambience on and off is always smooth, without any volume code.
#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.
Common mistakes
Section titled “Common mistakes”- Calling
play()before the sound has loaded.play()does nothing until the file is ready. After changingsrc,await source.load()first, or wait forAudio::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::…, notAudio::…. Compare withEventType.AudioPositional.Endfor those. - Replaying a one-shot with
play()alone. On a sound that is still playing,play()changes nothing. Callstop()first to rewind. - Expecting
stop()to fade. A script’sstop()andplay()are never faded. Disable the entity to use its Audio Fade, or tween the volume. - Looking sources up every frame. Call
findEntityandgetComponentonce instartupand 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.