Skip to content

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.

  • 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, maxDistance and distanceModel. Audio Zones mute it like any positional source.

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:

  1. Attack. The note rises from silence to full level over attack seconds. A short attack sounds percussive; a long one swells.
  2. Decay. It falls from full level to the sustain level over decay seconds.
  3. Sustain. It holds at sustain for as long as the note is held down.
  4. Release. Once the note is let go, it fades from its level to silence over release seconds.

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.

A note is either:

  • A name with its octave. A letter from A to G, an optional # (sharp) or b (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.

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.
AudioToneComponent.frequencyOf(note) 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.

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
AudioTone::ready EventType.AudioTone.Ready {} The synthesizer exists and notes can be played.
AudioTone::play EventType.AudioTone.Play { 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.
AudioTone::stop EventType.AudioTone.Stop {} stop(), or leaving the scene, cut notes that were sounding.

A short, clean beep when a button is pressed.

Blip.jx
#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);
});
}

How it works:

  • setProps shapes the sound once, in startup: 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.

Schedule a rising arpeggio and a final chord in one go.

Jingle.jx
#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);
});
}

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 or await between notes for music: timers depend on frames, while scheduled notes do not.

Write a tune as text and play it at any tempo, with a stop key.

Melody.jx
#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();
}

How it works:

  • 60 / BPM converts beats per minute to seconds per beat. Note i starts i beats 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 uses stop() 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.

Hold keys to sustain notes, like a piano: attack on key down, release on key up.

KeyboardPiano.jx
#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);
}
}
}

How it works:

  • isKeyPressed(key) is true every frame while the key is down. The held set remembers which notes are sounding, so the script reacts only to changes: a new press calls attack, a let-go calls release.
  • attack(note) holds the note at its sustain level for as long as needed; release(note) lets it fade over release seconds.
  • voices: 8 lets all eight keys sound together as a chord.

Hold a chord while a door is open and let it fade when it closes.

DoorPad.jx
#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());
}

How it works:

  • A long attack makes the chord swell in, and a long release lets 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.

Each stone plays its own note from where it is when something lands on it.

SteppingStones.jx
#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`);
});
}

How it works:

  • A Map from each stone’s entityId to its note and tone is built once in startup. event.entityId is the stone that sent the collision, so one listener serves every stone.
  • stone.children lists the objects under the stone; the child named Voice is 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.
  • Waiting between notes with timers. delay() or await between notes drifts with the frame rate. Pass the delay argument of play() 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 until release() or stop().
  • 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 release on short blips. With the default release of 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 with EventType.AudioTonePositional.Play.