Tones
Updated
A tone source is a small synthesizer that your scripts play notes on. It needs no sound file: you ask for 'C4' and it sounds. Use it for interface blips, chimes, success jingles, musical puzzles, a playable piano, or a whole melody written in code. There are two: Audio Tone (AudioToneComponent, comp-audio-tone) is heard the same everywhere, and Positional Audio Tone (PositionalAudioToneComponent, comp-audio-tone-positional) plays from its entity’s position and fades with distance.
Before you start
Section titled “Before you start”- Read Audio sources for what every audio entity shares: one source per entity, Signal Emitter events, hiding and disabling, Audio Fade and Audio Analyzer.
- The Positional Audio Tone takes the distance props described in Spatial audio:
refDistance,rolloffFactor,maxDistanceanddistanceModel. Audio Zones mute it like any positional source.
How a tone sounds
Section titled “How a tone sounds”Each note is a voice: an oscillator, the part that vibrates at the note’s pitch, shaped over time by an envelope. The envelope has four stages, often called ADSR:
- Attack. The note rises from silence to full level over
attackseconds. A short attack sounds percussive; a long one swells. - Decay. It falls from full level to the
sustainlevel overdecayseconds. - Sustain. It holds at
sustainfor as long as the note is held down. - Release. Once the note is let go, it fades from its level to silence over
releaseseconds.
A note let go during its attack or decay fades from the level it has reached, so short notes never click.
The waveform (oscillator) gives the note its colour: sine is pure and soft, triangle is mellow, square is hollow and retro, sawtooth is bright and buzzy.
The voices of a tone feed one output, so volume, Audio Fade, hiding, audio zones (positional tone only), the Audio Analyzer and audio filters treat a tone exactly like a sampled sound.
| Prop | Type | Default | Description |
|---|---|---|---|
oscillator |
'sine', 'square', 'triangle' or 'sawtooth' |
'triangle' |
Waveform of every voice. |
attack |
number | 0.005 |
Seconds from silence to full level. |
decay |
number | 0.1 |
Seconds from full level down to sustain. |
sustain |
number | 0.3 |
Level held while a note is down, from 0 to 1. |
release |
number | 1 |
Seconds from the held level to silence once a note is let go. |
voices |
integer | 8 |
Most notes sounding at once. |
note |
string or number | 'C4' |
The note play() uses when given none. Also the note the editor plays when you select the entity. |
duration |
number | 0.5 |
Seconds a play() note is held when given no duration. |
volume |
number | 1 |
Gain, from 0 to 1. |
Prop changes shape the next notes. A note already sounding keeps its waveform and envelope. A tone has no src and no autoplay: it sounds only when a script plays it.
Notes and chords
Section titled “Notes and chords”A note is either:
- A name with its octave. A letter from
AtoG, an optional#(sharp) orb(flat), and an octave number:'C4','F#3','Bb2'.'A4'is 440 Hz, and'C4'is middle C, about 261.63 Hz. - A frequency in hertz. A number greater than 0 and at most 20000, such as
440.
Pass an array of notes to play a chord: ['C4', 'E4', 'G4']. AudioToneComponent.frequencyOf(note) returns a note’s frequency in hertz, for example to map notes to visuals.
When a new note needs a voice and all voices are busy, the notes already fading out give way first, then the oldest; a note taken this way fades out quickly rather than clicking. Starting a note while the same pitch is held lets go of the held one first.
Methods
Section titled “Methods”| Method | What it does |
|---|---|
play(note?, duration?, delay?) |
Play a note or chord, starting delay seconds from now, held for duration seconds, then released. Defaults: the note and duration props, and a delay of 0. |
attack(note, delay?) |
Start holding a note or chord delay seconds from now. It sounds until it is released. |
release(note?, delay?) |
Let go of a held note or chord delay seconds from now. With no note, every held note. |
stop() |
Cut everything now: the notes sounding and those scheduled for later. |
isPlaying() |
true while any note is held, fading out or scheduled. |
setVolume(v) |
Set the gain at once, from 0 to 1. |
Audio |
The frequency of a note, in hertz. A static method: call it on the class. |
delay is measured on the audio clock, so notes scheduled with delays stay perfectly in time even if a frame is slow. That makes play(note, duration, delay) the right tool for melodies: schedule all the notes at once instead of waiting between them.
Events
Section titled “Events”A tone sends its events to the Signal Emitters on its entity, as AudioTone::… for the Audio Tone and AudioTonePositional::… for the positional one:
| Event | EventType constant |
Data | Sent when |
|---|---|---|---|
Audio |
Event |
{} |
The synthesizer exists and notes can be played. |
Audio |
Event |
{ note, delay } |
A note is scheduled by play() or attack(), one event per note of a chord. delay is the seconds until it sounds, 0 for a note that starts now. |
Audio |
Event |
{} |
stop(), or leaving the scene, cut notes that were sounding. |
Examples
Section titled “Examples”1. An interface blip
Section titled “1. An interface blip”A short, clean beep when a button is pressed.
#pragma lifecycle(startup)
let tone;
function startup() { tone = findEntity('UI Tone').getComponent(AudioToneComponent); tone.setProps({ oscillator: 'sine', attack: 0.002, decay: 0.06, sustain: 0, release: 0.05, volume: 0.5 });
on('ui/press', (event) => { if (event.eventType === EventType.UIButton.Press) tone.play('A5', 0.06); });}Three UI buttons that each play a short, clean beep when pressed: an Audio Tone shaped once and played by a Behavior script, with no sound file to load.
Press the buttons to hear the blip. Drag to orbit the camera, scroll to zoom.
How it works:
setPropsshapes the sound once, instartup: a near-instant attack, a fast decay to a sustain of 0, and a short release make a percussive blip.play('A5', 0.06)plays a high A for 60 milliseconds, then releases it.- Because nothing is loaded, the first blip sounds immediately, with no wait for a file.
2. A success jingle
Section titled “2. A success jingle”Schedule a rising arpeggio and a final chord in one go.
#pragma lifecycle(startup)
// Scene: an Audio Tone entity "Jingle Tone". Game code emits 'puzzle/solved'.let tone;
function startup() { tone = findEntity('Jingle Tone').getComponent(AudioToneComponent); tone.setProps({ oscillator: 'triangle', attack: 0.01, decay: 0.2, sustain: 0.4, release: 0.6 });
on('puzzle/solved', () => { const step = 0.12; tone.play('C5', step, 0); tone.play('E5', step, step); tone.play('G5', step, step * 2); tone.play(['C5', 'E5', 'G5', 'C6'], 0.8, step * 3); });}On puzzle/solved, an Audio Tone schedules a rising C major arpeggio and a final chord in one go.
Press Solve puzzle to hear the jingle.
How it works:
- Each call schedules one note: the third argument is its delay. All four calls run at once, and the audio clock plays them in perfect time.
- The last call passes an array, so four notes start together as a chord and are held for 0.8 s.
- Avoid
delay()timers orawaitbetween notes for music: timers depend on frames, while scheduled notes do not.
3. A melody from text
Section titled “3. A melody from text”Write a tune as text and play it at any tempo, with a stop key.
#pragma lifecycle(startup, update)
// Scene: a Positional Audio Tone entity "Music Box" on a table.// "-" is a rest. Each entry lasts one beat.const TUNE = 'E4 D4 C4 D4 E4 E4 E4 - D4 D4 D4 - E4 G4 G4 -';const BPM = 160;let box;
function playTune() { const beat = 60 / BPM; box.stop(); TUNE.split(' ').forEach((note, i) => { if (note !== '-') box.play(note, beat * 0.9, i * beat); });}
function startup() { box = findEntity('Music Box').getComponent(PositionalAudioToneComponent); box.setProps({ oscillator: 'sine', attack: 0.005, decay: 0.3, sustain: 0.2, release: 0.4, refDistance: 1 });}
function update() { if (Input.keyboard.isKeyReleased(Key.Space)) playTune(); if (Input.keyboard.isKeyReleased(Key.Escape)) box.stop();}A tune written as text, one note per beat with - for rests, is scheduled on a Positional Audio Tone at 160 beats a minute.
Click the scene, then press Space to play the tune and Escape to stop it. Orbit around the music box to hear it move.
How it works:
60 / BPMconverts beats per minute to seconds per beat. Noteistartsibeats from now.- Each note is held for 90% of a beat, so repeated notes stay distinct instead of merging.
stop()before playing clears notes still scheduled from an earlier play, so pressing Space twice never plays two tunes on top of each other. Escape usesstop()to cut everything, including notes scheduled for later.- Because it is a Positional Audio Tone, the tune comes from the music box and fades as the player walks away.
4. A playable keyboard
Section titled “4. A playable keyboard”Hold keys to sustain notes, like a piano: attack on key down, release on key up.
#pragma lifecycle(startup, update)
// Scene: an Audio Tone entity "Piano".const KEYS = [ [Key.A, 'C4'], [Key.S, 'D4'], [Key.D, 'E4'], [Key.F, 'F4'], [Key.G, 'G4'], [Key.H, 'A4'], [Key.J, 'B4'], [Key.K, 'C5'],];let piano;const held = new Set();
function startup() { piano = findEntity('Piano').getComponent(AudioToneComponent); piano.setProps({ oscillator: 'triangle', attack: 0.01, decay: 0.4, sustain: 0.5, release: 0.8, voices: 8 });}
function update() { for (const [key, note] of KEYS) { const down = Input.keyboard.isKeyPressed(key); if (down && !held.has(note)) { held.add(note); piano.attack(note); } else if (!down && held.has(note)) { held.delete(note); piano.release(note); } }}The keys A to K hold notes from C4 to C5 on an Audio Tone: attack on key down and release on key up, like a piano.
Click the scene, then hold the keys A, S, D, F, G, H, J and K to play from C4 to C5.
How it works:
isKeyPressed(key)is true every frame while the key is down. Theheldset remembers which notes are sounding, so the script reacts only to changes: a new press callsattack, a let-go callsrelease.attack(note)holds the note at itssustainlevel for as long as needed;release(note)lets it fade overreleaseseconds.voices: 8lets all eight keys sound together as a chord.
5. A pad that swells with a door
Section titled “5. A pad that swells with a door”Hold a chord while a door is open and let it fade when it closes.
#pragma lifecycle(startup)
// Scene: an Audio Tone entity "Pad". Door logic emits 'door/open' and 'door/close'.const CHORD = ['D3', 'F3', 'A3', 'C4'];let pad;
function startup() { pad = findEntity('Pad').getComponent(AudioToneComponent); pad.setProps({ oscillator: 'sawtooth', attack: 0.8, decay: 0.5, sustain: 0.6, release: 2.5, volume: 0.35 });
on('door/open', () => pad.attack(CHORD)); on('door/close', () => pad.release());}A sawtooth chord on an Audio Tone swells in over 0.8 s on door/open and fades out over 2.5 s on door/close.
Press Open door to swell the chord in, and Close door to let it fade.
How it works:
- A long
attackmakes the chord swell in, and a longreleaselets it linger after the door closes. release()with no argument lets go of every held note, so the script does not need to remember the chord.- A sawtooth is bright; pair it with a low-pass filter on the same entity for a warmer pad.
6. Musical stepping stones
Section titled “6. Musical stepping stones”Each stone plays its own note from where it is when something lands on it.
#pragma lifecycle(startup)
const voices = new Map();
function startup() { for (const note of ['C4', 'D4', 'E4', 'G4', 'A4']) { const stone = findEntity(`Stone ${note}`); const voice = stone.children.find((child) => child.name === 'Voice'); voices.set(stone.entityId, { note, tone: voice.getComponent(PositionalAudioToneComponent) }); }
on('stone', (event) => { if (event.eventType !== EventType.PhysicsCollider.CollisionEnter) return; const entry = voices.get(event.entityId); if (!entry) return; entry.tone.play(entry.note, 0.3); log(`${entry.note}: ${AudioToneComponent.frequencyOf(entry.note).toFixed(1)} Hz`); });}Five stones each carry a child Positional Audio Tone: bouncing balls land on them, and the stones' collision events play each one's note from where it sits.
With your sound on, click once to start the audio, then listen: every bounce plays the stone's note, and the log shows its frequency. Run the example again to replay. Drag to orbit the camera, scroll to zoom.
How it works:
- A
Mapfrom each stone’sentityIdto its note and tone is built once instartup.event.entityIdis the stone that sent the collision, so one listener serves every stone. stone.childrenlists the objects under the stone; the child namedVoiceis the tone entity.- Each stone has its own Positional Audio Tone, so the note comes from the stone that was hit.
AudioToneComponent.frequencyOf(note)is a static method, called on the class, that turns a note name into hertz.
Common mistakes
Section titled “Common mistakes”- Waiting between notes with timers.
delay()orawaitbetween notes drifts with the frame rate. Pass thedelayargument ofplay()instead. - Expecting a prop change to reshape a note already sounding. Props apply to the next notes. Set the sound before playing.
- Forgetting to release held notes. A note started with
attack()sounds untilrelease()orstop(). - Calling
play()every frame. That starts a new note each frame and quickly uses up every voice. React to changes, as the keyboard example does. - A high
releaseon short blips. With the defaultreleaseof 1 s, rapid blips overlap into a wash. Lower it for interface sounds. - Invalid notes. Write the octave (
'C4', not'C'), and keep frequencies above 0 and at most 20000. - Mixing up the event names. The positional tone sends
AudioTonePositional::…; compare withEventType.AudioTonePositional.Play.