coloX Audio API
coloX provides sound effect synthesis, music playback, PCM waveform playback, and microphone recording.
Contents
1. Sound Effects (SFX)
sfx(n [, channel [, offset]])
Plays a sound effect on the specified channel.
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
n | number | Required | Sound effect number 0..63 |
channel | number | -1 | Channel number |
offset | number | 0 | Starting note index (0..31) |
Special channel values:
| Value | Description |
|---|---|
-1 | Automatically choose a free channel (default) |
-2 | Pause sound effects on all channels |
Special sound effect numbers (effective only when channel is explicitly specified):
| Value | Description |
|---|---|
-1 | Stop the sound effect on the specified channel |
-2 | Stop sound effect looping on the specified channel |
sfx(3) -- Play sound effect 3 (automatic channel)
sfx(3, 2) -- Play sound effect 3 on channel 2
sfx(3, -2) -- Pause sound effect 3 on all channels
sfx(-1, 2) -- Stop channel 2
sfx(-2, 2) -- Stop looping on channel 2
-- Stop every channel: call once per channel
for ch = 0, 3 do sfx(-1, ch) end
__sfx__ Section Data Format
Sound effects played by sfx(n) are defined in the cartridge's __sfx__ section, one sfx per line (numbered 0-63).
168 hexadecimal characters per line = header (8 hex) + 32 notes (5 hex each).
⚠ Line length must be ≥ 167 characters: shorter lines are entirely ignored, leaving the sfx empty/silent (without an error, a common pitfall).
header(8 hex):
| Field | Length | Description |
|---|---|---|
| editorMode | 2 hex | Editor mode |
| speed | 2 hex | Note duration (larger = slower) |
| loopRangeStart | 2 hex | Loop starting note |
| loopRangeEnd | 2 hex | Loop ending note |
Each note (5 hex) = pitch[2] + wave[1] + vol[1] + eff[1]:
| Field | Range | Description |
|---|---|---|
| pitch | 0-63 | Pitch: 0=lowest (C2), +1 per semitone, +12 per octave (24≈middle C/C4, 36=C5, 48=C6) |
| wave | 0-7 | Waveform: 0 tri / 1 tilted-saw / 2 saw / 3 square / 4 pulse / 5 organ / 6 noise / 7 phaser (>7 triggers the custom flag) |
| vol | 0-7 | Volume: 0=silent. Only 3 bits; values 8-15 wrap modulo 8 (8 is silent) |
| eff | 0-7 | Effect: 0 none / 1 slide / 2 vibrato / 3 drop / 4 fade-in / 5 fade-out / 6 fast arp / 7 slow arp |
⚠ Low frequencies are inaudible: handheld/small speakers respond poorly below 100Hz; pitch 0-7 (C2-G2 ≈ 65-98Hz) is barely audible. Recommended bass pitch: ≥12 (C3 ≈ 131Hz); percussion/drum noise pitch: 16-24; mid/high melody: 24-48.
⚠ The coloX-4 (round-screen) host has two audio pitfalls (tested with coloXtest;
coloX-4P/coloX-PICO8/ physical devices are unaffected, so tri works normally in mario and similar cartridges):
- tri(wave0) is silent on the host—use saw(wave2) for sfx/bgm (test tilted-saw/square/noise before relying on them). noise(6) has low amplitude; raise vol for drums.
- When a cartridge includes music data (
__music__/__musicd__), notes triggered directly bysfx()require a nonzero effect (eff1-7; eff5 fade-out recommended); eff0 notes are silent in directsfx()calls. Note: eff0 works inside music patterns (played bymusic()); only the combination "directsfx()+ cartridge containing music" is silent.Observed behavior: bgm uses saw+eff0 (
music(), audible); food/death effects use saw+eff5 (directsfx(), audible).coloX-4Pavoids both pitfalls and can use tri/eff0 normally.
The text format uses 5 hex per note (pitch2+wave1+vol1+eff1), while the in-memory binary format uses 2 bytes/note (little-endian).
__sfx__text and__sfxd__binary pack fields differently; do not mix their calculations.
Generation recommendation: Generate with a script rather than counting manually. Python:
def note(p, w, v, e):
return '%02x%01x%01x%01x' % (p, w, v, e)
def sfxline(mode, speed, loop_s, loop_e, notes): # At most 32 notes
return '%02x%02x%02x%02x' % (mode, speed, loop_s, loop_e) + ''.join(notes) + '00000' * (32 - len(notes))
# Food effect: rising saw C-E-G, vol7, eff5 (direct sfx on coloX-4 needs a nonzero effect; see the two audio pitfalls above)
sfxline(0, 0x05, 0, 0, [note(36,2,7,5), note(40,2,7,5), note(43,2,7,5)])
# → 0005000024275282752b275 + 29×00000 (168 hex digits total)
Examples:
- Rising "ding" (saw fade-out, food pickup, safe for direct coloX-4 sfx):
00050000+24275 28275 2b275+ 29×00000 - Descending "buzz" with fade-out (saw fade-out, death):
00090000+28275 20275 18265 10255 08245+ 27×00000
__sfxd__ Section Data Format (Standard Binary, Commonly Used)
__sfx__ above is coloX's text format; __sfxd__ is the standard binary format, used by many clx files (especially ports), and is also played by sfx(n). Both are supported; choose as needed.
One sfx per line, 68 bytes = 136 hex = 32 notes (2 bytes each, little-endian) + 4 trailing bytes.
- Each note (2 bytes, little-endian) is 16-bit:
pitch(6) | wave(3) | vol(3) | eff(3) | custom(1), i.e.value = (eff<<12)|(vol<<9)|(wave<<6)|pitch, low byte first. - 4 trailing bytes after the notes:
editorMode+speed+loopRangeStart+loopRangeEnd. - Field ranges match
__sfx__(pitch 0-63 / wave 0-7 / vol 0-7 / eff 0-7); the low-frequency pitfalls above also apply.
Python generation (do not count manually):
def pn(p, w, v, e):
val = (e<<12)|(v<<9)|(w<<6)|p
return '%02x%02x' % (val & 0xff, (val>>8) & 0xff) # 2 bytes, little-endian
def psfx(mode, speed, ls, le, notes): # 32 notes
return ''.join(notes) + '%02x%02x%02x%02x' % (mode, speed, ls, le)
# Rising saw C-E-G, vol7, eff5 (direct sfx on coloX-4 needs a nonzero effect)
psfx(0, 5, 0, 0, [pn(36,2,7,5), pn(40,2,7,5), pn(43,2,7,5)] + ['0000']*29)
# → a45ea85eab5e + 29×0000 + 00050000 (136 hex digits total)
⚠ Generate hex with a generator; do not write it by hand: manual sfx hex easily misaligns bytes or corrupts trailing bytes, making the entire effect silent without an error (experienced in this repository: manually written sfx stayed silent, while the same parameters generated by a script worked immediately). The
pn()/psfx()above are correct and ready to use.
✅ Audible coloX-4 parameters (tested): saw(wave2) + vol 3-7 + melody pitch≥24 / bass≥12. Use eff≠0 for notes triggered directly by
sfx()(eff5 recommended); eff0 works insidemusic()patterns.speedcontrols note duration (ticks/note, larger=slower): game effects 8-16, bgm 14-32.coloX-4Pavoids both pitfalls and can use tri/eff0 normally.
2. Music
music(n [, fade_len [, channel_mask]])
Plays music.
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
n | number | Required | Music pattern number 0..63; -1 stops playback |
fade_len | number | 0 | Transition time (milliseconds) |
channel_mask | number | All | Channels reserved for music (bitfield) |
channel_mask: A bitfield specifying channels dedicated to music. Unreserved channels may be used for sound effects.
music(0) -- Play music 0
music(0, 1000) -- Play music 0 with a 1-second transition
music(0, nil, 7) -- Play only on channels 0-2 (1|2|4 = 7)
music(-1) -- Stop music
Explicitly specifying a sound effect channel ignores reservations and uses that channel directly. Note: automatic channel selection currently does not inspect the music reservation mask; sound effects may occupy any free channel. For strict separation, play effects on fixed channels outside the reserved mask.
__music__ Section Data Format
Music played by music(n) is defined in the cartridge's __music__ section, one pattern per line (numbered 0-63).
Each line = flag[2] + space + 4 channels[8] (2 hex per channel), totaling 11 characters.
⚠ Line length must be ≥ 11 characters; shorter lines are ignored.
- flag (2 hex) bits:
bit0begin-loop,bit1end-loop (return to the latest begin-loop after playback),bit2stop,bit3mode. Common values:00advance to the next pattern,03loop a single pattern (begin+end),04stop. - 4 channels (2 hex each): Put an sfx number (0-63) in each channel to play that sfx; use
00for unused channels.
music(n) plays the sfx specified by pattern n on 4 channels in parallel—a bgm passage assigns melody/bass/drums and other sfx to different channels.
Example (pattern 0, single-pattern loop: ch0 plays sfx2 melody, ch2 plays sfx3 bass, ch1/ch3 empty):
__music__
03 02000300
flag=03 (begin+end loop), ch0=02, ch1=00, ch2=03, ch3=00; use music(0) to loop.
ℹ Use
__musicd__for multipart bgm: The standard binary__musicd__format is easier for multipart bgm/ports, matching reference cartridges such as mario. Text__music__also works, but binary__musicd__is more common. To avoid writing patterns temporarily, trigger multiple sfx periodically in_update:if t % 128 == 0 then sfx(2) sfx(3) sfx(4) end.
__musicd__ Section Data Format (Standard Binary, Commonly Used)
__music__ above is text; __musicd__ is the standard binary format, also played by music(n), with more reliable multichannel behavior (used by many clx files).
One pattern per line, 4 bytes = 8 hex: each channel byte = sfx number(bit5-0) | SILENT(bit6) | flag(bit7).
- bit6 (
0x40) = SILENT: Setting it mutes the channel (for unused channels; accidentally setting it on an active channel makes it silent). - bit7 (
0x80) = flag, depending on channel position: byte0 = begin-loop, byte1 = end-loop (return to the latest begin-loop after playback), byte2 = stop (stop at this pattern after playback), byte3 = unused. - Loop one pattern forever: Set both begin and end in pattern 0 (bit7 of byte0 and byte1), so it returns to itself. Example
82830440: ch0=sfx2|begin, ch1=sfx3|end, ch2=sfx4, ch3=silent →music(0)loops. - Flags are optional: Most mario / astropocalypse_p patterns omit flags and rely on
music(n)advancing n→n+1→… until a stop flag ormusic(-1). music(n)plays pattern n's sfx on 4 channels in parallel; add begin/end flags to the corresponding patterns to loop.
Example (pattern 0, looping: ch0=sfx2 melody + ch1=sfx3 bass + ch2=sfx4 drums, ch3 empty):
82 83 04 40 → byte0=82 (sfx2 | START), byte1=83 (sfx3 | LOOP), byte2=04 (sfx4), byte3=40 (SILENT unused channel). Loop with music(0).
Music Arrangement (Building bgm with sfx and Patterns)
A bgm passage = multiple sfx (note sequences) + patterns (arranging sfx on 4 channels) + song structure (pattern sequences/loops).
1. Channel roles (one sfx per channel, all 4 playing in parallel):
| Channel | Typical use | sfx characteristics |
|---|---|---|
| ch0 | Main melody | Mid/high pitch 24-48, tri/square |
| ch1 | Countermelody / harmony | Harmony following the melody |
| ch2 | Bass | Bass line, pitch ≥12 (from C3), saw/triangle |
| ch3 | Drums / percussion | noise(wave=6), pitch 16-24, alternating kick/snare |
2. sfx design: One sfx per channel, 32 notes per passage. Melody sfx contains the melody pitch sequence; bass sfx contains the bass rhythm (chord roots); drum sfx contains the percussion rhythm (alternating kick/snare/rest).
3. Pattern (one __musicd__ line): One sfx number for each of 4 channels → one pattern, lasting the 32 notes of one sfx.
4. Song structure: Chain patterns into a song. music(n) starts at pattern n and automatically advances to n+1, stopping only at a stop flag or music(-1). Mark loop regions with begin/end loop flags.
5. Rhythm synchronization: Use the same speed for the 4 sfx in a pattern to keep all parts aligned.
Example: mario pattern 24 = 879B6869 → ch0=sfx7 (begin flag) and ch1=sfx27 (end flag) play in parallel; ch2=0x68/ch3=0x69 have bit6 set and are silent channels (the low 6-bit number is irrelevant when bit6 is 1; 0x40+n is the conventional silent representation). mario chains patterns 0-63 into multiple bgm passages, switching scenes with music(24)/music(23), etc.
Writing good melody/harmony requires music theory (chord progressions, modes). If unsure, borrow sfx/music data from existing clx cartridges (such as mario), as this game does, or copy a passage and modify it.
3. Wave Playback
wave(data [, from, to, audiotype [, hz [, bpp]]])
Plays PCM audio directly. Default: 16000Hz, 16-bit little-endian (hz/bpp accept only 0 (default) or 16000/16; other values reject the call and return 0).
Parameters:
| Parameter | Type | Description |
|---|---|---|
data | string/special character | PCM audio data |
from, to | number | Data range (1-based inclusive, in bytes; from defaults to 1) |
audiotype | number | Audio type |
hz | number | Sample rate (0 or 16000) |
bpp | number | Bit depth (0 or 16) |
audiotype values:
| Value | Type |
|---|---|
| 0 (default) | Raw PCM data |
| 1 | ADPCM-compressed data |
| 2 | G.711A-compressed data |
| 3 | Opus-compressed data |
Special data values:
| Value | Description |
|---|---|
'I' | Initialize (allocate internal resources) |
'R' | Reset the data buffer |
'D' | Release resources |
'L' | Return bytes buffered for playback |
| No arguments | Return bytes of remaining writable space |
Returns: produced, consumed
| Return value | Description |
|---|---|
produced | Amount decoded and written to the internal buffer (bytes for PCM; samples for ADPCM/G.711A—ADPCM produces 2 samples per input byte); queries/controls (L/I/R/D, no arguments) return capacity information |
consumed | Bytes actually consumed from data in this call (second return value); may be less than the length of data (e.g. an incomplete trailing Opus packet). For streaming, retain the remaining data for the next call |
consumedis the actual number of bytes read fromdataby the decoder (counted directly, not inferred from output). PCM = bytes written; ADPCM (4:1) = actual pointer advancement; G.711A (2:1) = actual reads after clamping; Opus follows internal packet boundaries and excludes an incomplete trailing packet. When the internal buffer is nearly full (clamping),consumedmay be shorter thandata; keep the remainder for the next call.
-- Stream ADPCM audio
local wavefile = {
#blob :ea:16000: canon.pcm
}
local curpos = 0
wave('I') -- Initialize
function _update()
if wave() > 16000 then -- Buffer space is available
curpos = curpos + 1
local chunk = wavefile[curpos]
if chunk then
wave(chunk, nil, nil, 1) -- Play ADPCM
else
curpos = 0 -- Loop
end
end
end
function _draw()
cls(dark_green)
end
4. Microphone
micpoll([flag, maxlen, audiotype])
Gets microphone recording data. The system microphone functionality must be enabled.
Parameters:
| Parameter | Type | Description |
|---|---|---|
flag | number | Operation flag (see below) |
maxlen | number | Data amount limit |
audiotype | number | Audio type (0=PCM, 1=ADPCM, 2=G.711A, 3=Opus) |
flag values:
| Value | Description |
|---|---|
1 | Clear the buffer |
2 | Get valid data length (16-bit units) |
3 | Get data; maxlen is the maximum amount (16-bit units) |
4 | Get FFT data |
flag=4 (FFT) returns:
avg, maxidx, maxval, [ffts]
avg— averagemaxidx— peak frequency indexmaxval— peak amplitudeffts— FFT spectrum array;maxlenis the sample count (0=do not return the array)
-- Record and play back microphone audio
wave('I')
micpoll(1) -- Clear the buffer
function _update()
local d = micpoll(nil, nil, 1) -- Read in ADPCM format
if d then
wave(d, nil, nil, 1) -- Play
end
end
function _draw()
cls(dark_green)
end
-- FFT spectrum analysis
function _update()
local avg, maxidx, maxval, ffts = micpoll(4, 32)
if ffts then
for i, v in ipairs(ffts) do
-- Draw spectrum bars
local h = flr(v / 10)
rectfill(i * 8, 200 - h, i * 8 + 6, 200, green)
end
end
end
5. Complete API Index
| Function | Description |
|---|---|
sfx(n [, channel [, offset]]) | Play/stop sound effects |
music(n [, fade_len [, channel_mask]]) | Play/stop music |
wave(data [, from, to, audiotype [, hz [, bpp]]]) | PCM/ADPCM/G711A/Opus waveform playback |
wave('I') | Initialize waveform resources |
wave('R') | Reset buffer |
wave('D') | Release waveform resources |
wave() | Return remaining writable space (bytes) |
wave('L') | Return buffered bytes awaiting playback |
micpoll([flag, maxlen, audiotype]) | Microphone recording/FFT |
Audio status is also available through
stat():stat(16..19)/stat(46..49)give the current sfx number per channel;stat(20..23)/stat(50..53)give the current note index (see system.md).