Skip to main content

coloX Audio API

coloX provides sound effect synthesis, music playback, PCM waveform playback, and microphone recording.


Contents​

  1. Sound effects (SFX)
  2. Music
  3. Wave playback
  4. Microphone
  5. Complete API index

1. Sound Effects (SFX)​

sfx(n [, channel [, offset]])​

Plays a sound effect on the specified channel.

Parameters:

ParameterTypeDefaultDescription
nnumberRequiredSound effect number 0..63
channelnumber-1Channel number
offsetnumber0Starting note index (0..31)

Special channel values:

ValueDescription
-1Automatically choose a free channel (default)
-2Pause sound effects on all channels

Special sound effect numbers (effective only when channel is explicitly specified):

ValueDescription
-1Stop the sound effect on the specified channel
-2Stop 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):

FieldLengthDescription
editorMode2 hexEditor mode
speed2 hexNote duration (larger = slower)
loopRangeStart2 hexLoop starting note
loopRangeEnd2 hexLoop ending note

Each note (5 hex) = pitch[2] + wave[1] + vol[1] + eff[1]:

FieldRangeDescription
pitch0-63Pitch: 0=lowest (C2), +1 per semitone, +12 per octave (24≈middle C/C4, 36=C5, 48=C6)
wave0-7Waveform: 0 tri / 1 tilted-saw / 2 saw / 3 square / 4 pulse / 5 organ / 6 noise / 7 phaser (>7 triggers the custom flag)
vol0-7Volume: 0=silent. Only 3 bits; values 8-15 wrap modulo 8 (8 is silent)
eff0-7Effect: 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):

  1. 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.
  2. When a cartridge includes music data (__music__/__musicd__), notes triggered directly by sfx() require a nonzero effect (eff1-7; eff5 fade-out recommended); eff0 notes are silent in direct sfx() calls. Note: eff0 works inside music patterns (played by music()); only the combination "direct sfx() + cartridge containing music" is silent.

Observed behavior: bgm uses saw+eff0 (music(), audible); food/death effects use saw+eff5 (direct sfx(), audible). coloX-4P avoids 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 inside music() patterns. speed controls note duration (ticks/note, larger=slower): game effects 8-16, bgm 14-32. coloX-4P avoids both pitfalls and can use tri/eff0 normally.


2. Music​

music(n [, fade_len [, channel_mask]])​

Plays music.

Parameters:

ParameterTypeDefaultDescription
nnumberRequiredMusic pattern number 0..63; -1 stops playback
fade_lennumber0Transition time (milliseconds)
channel_masknumberAllChannels 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: bit0 begin-loop, bit1 end-loop (return to the latest begin-loop after playback), bit2 stop, bit3 mode. Common values: 00 advance to the next pattern, 03 loop a single pattern (begin+end), 04 stop.
  • 4 channels (2 hex each): Put an sfx number (0-63) in each channel to play that sfx; use 00 for 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 or music(-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):

ChannelTypical usesfx characteristics
ch0Main melodyMid/high pitch 24-48, tri/square
ch1Countermelody / harmonyHarmony following the melody
ch2BassBass line, pitch ≥12 (from C3), saw/triangle
ch3Drums / percussionnoise(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:

ParameterTypeDescription
datastring/special characterPCM audio data
from, tonumberData range (1-based inclusive, in bytes; from defaults to 1)
audiotypenumberAudio type
hznumberSample rate (0 or 16000)
bppnumberBit depth (0 or 16)

audiotype values:

ValueType
0 (default)Raw PCM data
1ADPCM-compressed data
2G.711A-compressed data
3Opus-compressed data

Special data values:

ValueDescription
'I'Initialize (allocate internal resources)
'R'Reset the data buffer
'D'Release resources
'L'Return bytes buffered for playback
No argumentsReturn bytes of remaining writable space

Returns: produced, consumed

Return valueDescription
producedAmount 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
consumedBytes 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

consumed is the actual number of bytes read from data by 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), consumed may be shorter than data; 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:

ParameterTypeDescription
flagnumberOperation flag (see below)
maxlennumberData amount limit
audiotypenumberAudio type (0=PCM, 1=ADPCM, 2=G.711A, 3=Opus)

flag values:

ValueDescription
1Clear the buffer
2Get valid data length (16-bit units)
3Get data; maxlen is the maximum amount (16-bit units)
4Get FFT data

flag=4 (FFT) returns:

avg, maxidx, maxval, [ffts]

  • avg — average
  • maxidx — peak frequency index
  • maxval — peak amplitude
  • ffts — FFT spectrum array; maxlen is 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​

FunctionDescription
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).