← audio · API reference · version 0.2.8
3 file(s), 448 lines. This is the source the published version ships, and it is loft — the library is written in the same language you call it from.
Public items
A worked example is a call site the author chose as the thing to read first. Call sites are every line naming the item, found mechanically over the source with comments excluded — so an item with no worked example is not an item nobody uses.
| Item | Defined | Worked example | Call sites |
|---|---|---|---|
init fn | 76 | — | 20 28 35 46 57 66 … (16 total) |
rate fn | 81 | — | 31 39 51 76 77 29 |
has_vorbis fn | 87 | — | 173 |
load fn | 93 | — | 150 162 175 194 |
load_bytes fn | 100 | — | 195 |
load_samples fn | 107 | — | 22 24 101 197 |
unload fn | 113 | — | none in this package |
clip_frames fn | 118 | — | 152 178 |
clip_rate fn | 122 | — | 152 177 |
clip_channels fn | 126 | — | 152 163 177 |
play fn | 133 | — | 27 36 37 48 58 69 … (19 total) |
play_raw fn | 140 | — | 141 |
stop fn | 146 | — | 112 115 |
stop_all fn | 151 | — | 39 117 118 |
playing fn | 156 | — | 28 32 38 41 86 116 … (8 total) |
set_volume fn | 161 | — | 127 |
set_pan fn | 166 | — | 129 |
seek fn | 172 | — | 134 135 |
render fn | 179 | — | 37 38 38 49 59 71 … (17 total) |
start fn | 192 | — | 134 136 24 26 |
stop_output fn | 197 | — | 33 |
output_running fn | 202 | — | 25 34 |
output_frames fn | 207 | — | 13 31 |
src/audio.loft
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// audio — clips, voices and one mix, the same on every target.
//
// The engine (c/audio_engine.c) holds the clips and the playing voices and RENDERS: `render`
// answers the next stereo frames of the mix as 16-bit samples. A platform's OUTPUT asks the
// engine for frames on its own thread (c/audio_out.c): `start()` opens it — the system's sound
// device on a desktop (miniaudio), the I2S stream on a Tanmatsu — and from then on every voice
// is heard. Without `start`, `render` is the way out, so every rule below is checkable on a
// machine with no sound device. The calls are `graphics`' audio calls (`audio_play(clip, volume, looping, pan,
// start)` and the rest), so a program written against those moves over unchanged.
//
// The mix, per output frame: each voice reads its clip with linear interpolation, resampled
// from the clip's rate to the output rate; its volume scales it and its pan places it by Web
// Audio's StereoPannerNode law (equal-power: a mono clip at the centre is cos(pi/4) = 0.7071 on
// each side); the voices are summed, clamped to [-1, 1] and written as round(s * 32767).
//
// Handles: a clip or a voice is a positive integer, null on failure. A voice handle names
// one playing, never a slot: once a voice ends, its handle acts on nothing, even after its
// slot plays something else.
fn ae_out_open(mode: integer) -> integer;
#c "ae_out_open" "int64_t(int64_t)"
fn ae_out_close();
#c "ae_out_close" "void(void)"
fn ae_out_running() -> integer;
#c "ae_out_running" "int64_t(void)"
fn ae_out_frames() -> integer;
#c "ae_out_frames" "int64_t(void)"
fn ae_init(rate: integer);
#c "ae_init" "void(int64_t)"
fn ae_rate() -> integer;
#c "ae_rate" "int64_t(void)"
fn ae_vorbis() -> integer;
#c "ae_vorbis" "int64_t(void)"
fn ae_load(bytes: const vector<u8>) -> integer;
#c "ae_load" "int64_t(const uint8_t*, int64_t)"
fn ae_load_pcm(samples: const vector<single>, rate: integer) -> integer;
#c "ae_load_pcm" "int64_t(const float*, int64_t, int64_t)"
fn ae_unload(clip: integer);
#c "ae_unload" "void(int64_t)"
fn ae_clip_frames(clip: integer) -> integer;
#c "ae_clip_frames" "int64_t(int64_t)"
fn ae_clip_rate(clip: integer) -> integer;
#c "ae_clip_rate" "int64_t(int64_t)"
fn ae_clip_channels(clip: integer) -> integer;
#c "ae_clip_channels" "int64_t(int64_t)"
fn ae_play(clip: integer, p: const vector<float>) -> integer;
#c "ae_play" "int64_t(int64_t, const loft_float*, int64_t)"
fn ae_play_raw(samples: const vector<single>, rate: integer, p: const vector<float>) -> integer;
#c "ae_play_raw" "int64_t(const float*, int64_t, int64_t, const loft_float*, int64_t)"
fn ae_stop(voice: integer);
#c "ae_stop" "void(int64_t)"
fn ae_stop_all();
#c "ae_stop_all" "void(void)"
fn ae_playing(voice: integer) -> integer;
#c "ae_playing" "int64_t(int64_t)"
fn ae_set_volume(voice: integer, p: const vector<float>);
#c "ae_set_volume" "void(int64_t, const loft_float*, int64_t)"
fn ae_set_pan(voice: integer, p: const vector<float>);
#c "ae_set_pan" "void(int64_t, const loft_float*, int64_t)"
fn ae_seek(voice: integer, p: const vector<float>) -> integer;
#c "ae_seek" "int64_t(int64_t, const loft_float*, int64_t)"
fn ae_render(out: vector<i32>);
#c "ae_render" "void(int32_t*, int64_t)"
// A handle the engine answered, null for its 0.
fn handle(h: integer) -> integer? {
if h <= 0 { return null; }
h
}
/// Set the output rate (frames per second, 44100 unless set) and stop every voice; the
/// loaded clips stay. A platform's output layer calls this with the rate its device runs at.
pub fn init(rate: integer = 44100) {
ae_init(rate);
}
/// The output rate the mix renders at.
pub fn rate() -> integer {
ae_rate()
}
/// Does this build decode OGG Vorbis? Every target but the freestanding wasm build (the Rust
/// writer's page) does.
pub fn has_vorbis() -> boolean {
ae_vorbis() != 0
}
/// Load a clip from a WAV (PCM 8/16/24/32-bit or float, mono or stereo) or OGG Vorbis file.
/// Null when the file cannot be read or decoded.
pub fn load(path: text) -> integer? {
bytes = read_bytes(path) ?? [];
if len(bytes) == 0 { return null; }
handle(ae_load(bytes))
}
/// Load a clip from a file's bytes already in memory.
pub fn load_bytes(bytes: const vector<u8>) -> integer? {
if len(bytes) == 0 { return null; }
handle(ae_load(bytes))
}
/// A mono clip from samples in [-1, 1] at `sample_rate` — a sound made in loft, kept to be
/// played again.
pub fn load_samples(samples: const vector<single>, sample_rate: integer) -> integer? {
if len(samples) == 0 { return null; }
handle(ae_load_pcm(samples, sample_rate))
}
/// Unload a clip; every voice playing it stops.
pub fn unload(clip: integer) {
ae_unload(clip);
}
/// A clip's length in frames, its rate and its channel count (1 or 2); 0 for no clip.
pub fn clip_frames(clip: integer) -> integer {
ae_clip_frames(clip)
}
pub fn clip_rate(clip: integer) -> integer {
ae_clip_rate(clip)
}
pub fn clip_channels(clip: integer) -> integer {
ae_clip_channels(clip)
}
/// Play a clip: `volume` 0.0-1.0, `looping` repeats it until it is stopped, `pan` places it
/// from -1 (left) through 0 (centre) to 1 (right), `start` begins that many seconds in.
/// Answers the voice, or null when the clip is unknown or every voice is busy (64 play at once).
pub fn play(clip: integer, volume: float, looping: boolean = false, pan: float = 0.0,
start: float = 0.0) -> integer? {
l = if looping { 1.0 } else { 0.0 };
handle(ae_play(clip, [volume, l, pan, start]))
}
/// Play mono samples in [-1, 1] at `sample_rate` once; the samples are released when it ends.
pub fn play_raw(samples: const vector<single>, sample_rate: integer, volume: float) -> integer? {
if len(samples) == 0 { return null; }
handle(ae_play_raw(samples, sample_rate, [volume]))
}
/// Stop a voice. A voice that already ended is left alone, as is whatever plays in its place.
pub fn stop(voice: integer) {
ae_stop(voice);
}
/// Stop every voice — a pause menu, a scene change, a game over.
pub fn stop_all() {
ae_stop_all();
}
/// Is this voice still playing?
pub fn playing(voice: integer) -> boolean {
ae_playing(voice) != 0
}
/// Set a playing voice's volume, 0.0-1.0.
pub fn set_volume(voice: integer, volume: float) {
ae_set_volume(voice, [volume]);
}
/// Move a playing voice across the stereo field, -1 (left) to 1 (right).
pub fn set_pan(voice: integer, pan: float) {
ae_set_pan(voice, [pan]);
}
/// Jump a playing voice to `seconds` into its clip. False for a voice that ended, and for a
/// position past the end of a clip that does not loop (a looping clip wraps).
pub fn seek(voice: integer, seconds: float) -> boolean {
ae_seek(voice, [seconds]) != 0
}
/// The next `frames` frames of the mix: 2 * frames samples, left and right interleaved, each
/// a 16-bit value (-32767 to 32767). Advances every voice; a voice that reaches the end of a
/// clip it does not loop ends.
pub fn render(frames: integer) -> vector<i32> {
out: vector<i32> = [0 as i32; 2 * frames];
if frames > 0 { ae_render(out); }
out
}
// --- Output ---
/// Start the output, so every voice is heard: the system's sound device on a desktop, the
/// board's I2S stream on a Tanmatsu. `silent` plays at real-time pace into no device at all,
/// for a test or a server. Answers whether it runs: false where this machine has no output
/// (no sound device, or a browser build), and the engine then only renders. Starting twice
/// is starting once. Set the rate with `init` before this.
pub fn start(silent: boolean = false) -> boolean {
ae_out_open(if silent { 1 } else { 0 }) != 0
}
/// Stop the output; the voices keep their place and play on from it after the next `start`.
pub fn stop_output() {
ae_out_close();
}
/// Is the output running?
pub fn output_running() -> boolean {
ae_out_running() != 0
}
/// How many stereo frames the output has taken since it started — the clock of what was heard.
pub fn output_frames() -> integer {
ae_out_frames()
}
tests/output.loft
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// The output layer, run for real: `start(true)` opens a device that takes frames at real-time
// pace from the output thread and plays them into nothing. A clip of 4410 frames at 44100 Hz
// (0.1 s) is heard through it and ends, with no `render` from this thread, so the frames the
// output took are the mix running on its own. Each wait polls with a 3 s deadline on `ticks`.
use audio;
// Wait until the output has taken `frames` frames, or 3 s pass; answers whether it did.
fn wait_frames(frames: integer) -> boolean {
deadline = ticks() + 3000000;
while audio::output_frames() < frames {
if ticks() > deadline { return false; }
}
true
}
fn main() {
audio::init(44100);
samples: vector<single> = [0.5f; 4410];
c = audio::load_samples(samples, 44100) ?? 0;
assert(c > 0, "the clip loads");
assert(audio::start(true), "the null device opens");
assert(audio::output_running(), "running");
assert(audio::start(true), "starting twice is starting once");
v = audio::play(c, 1.0) ?? 0;
assert(audio::playing(v), "the voice plays");
// The device takes frames in periods; 4410 frames of clip are gone by the time it has taken
// 4410 + two periods of 1024 more (it began counting before the voice started).
assert(wait_frames(4410 + 2048 + 4410), "the output took frames: {audio::output_frames()}");
assert(!audio::playing(v), "the clip was heard to its end by the output alone");
audio::stop_output();
assert(!audio::output_running(), "stopped");
// Stopped, the engine renders again, and a voice started now waits for it.
w = audio::play(c, 1.0) ?? 0;
out = audio::render(10);
assert(out[0] == 11585 && audio::playing(w), "render is the way out again: {out[0]}");
audio::stop_all();
}
tests/render.loft
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// The engine's mix, read back through `render`. Every expected sample is computed by hand in
// the cell's comment. The clip values are binary fractions and the pans the two edges, where
// the gains are exactly 1 and 0, so the arithmetic is exact: a 16-bit sample is
// round(s * 32767), halves away from zero (0.5 -> 16383.5 -> 16384, -0.25 -> -8192).
// Output rate 8000 and clips at 8000, so one clip frame is one output frame, except where a
// cell says otherwise. Each cell starts from `init`, which stops every voice.
use audio;
// Every other sample, from `start`: the left channel (0) or the right (1) as text.
fn side(out: const vector<i32>, ch: integer) -> text {
t = "";
i = ch;
while i < len(out) {
t += "{out[i] ?? -99999},";
i += 2;
}
t
}
fn clip(samples: const vector<single>) -> integer {
audio::load_samples(samples, 8000) ?? 0
}
fn main() {
audio::init(8000);
assert(audio::rate() == 8000, "the output rate");
}
// Hard left (pan -1): the left gain is cos 0 = 1, the right sin 0 = 0. The clip ends after
// four frames and the voice with it.
fn test_hard_left() {
audio::init(8000);
c = clip([0.5f, -0.25f, 1.0f, 0.0f]);
v = audio::play(c, 1.0, false, -1.0) ?? 0;
out = audio::render(6);
assert(side(out, 0) == "16384,-8192,32767,0,0,0,", "left: {side(out, 0)}");
assert(side(out, 1) == "0,0,0,0,0,0,", "right: {side(out, 1)}");
assert(!audio::playing(v), "a clip that does not loop ends its voice");
}
// Hard right at volume 0.5: 0.25 -> 8192, -0.125 -> -4096, 0.5 -> 16384, 0 -> 0 on the right.
fn test_hard_right_half_volume() {
audio::init(8000);
c = clip([0.5f, -0.25f, 1.0f, 0.0f]);
audio::play(c, 0.5, false, 1.0);
out = audio::render(4);
assert(side(out, 1) == "8192,-4096,16384,0,", "right: {side(out, 1)}");
assert(side(out, 0) == "0,0,0,0,", "left: {side(out, 0)}");
}
// A mono clip at the centre is cos(pi/4) = 0.70710677 on each side: 0.25 -> 5792.44 -> 5792,
// 0.75 -> 17377.32 -> 17377 (measured as single arithmetic does it).
fn test_centre_pan_is_equal_power() {
audio::init(8000);
audio::play(clip([0.25f, 0.75f]), 1.0);
out = audio::render(2);
assert(side(out, 0) == "5792,17377,", "left: {side(out, 0)}");
assert(side(out, 1) == "5792,17377,", "right: {side(out, 1)}");
}
// Two full-scale voices sum to 2 and -2, which clamp to the 16-bit edge.
fn test_sum_clamps() {
audio::init(8000);
up = clip([1.0f]);
down = clip([-1.0f]);
audio::play(up, 1.0, false, -1.0);
audio::play(up, 1.0, false, -1.0);
first = audio::render(1);
audio::play(down, 1.0, false, -1.0);
audio::play(down, 1.0, false, -1.0);
second = audio::render(1);
assert(side(first, 0) == "32767,", "2.0 clamps: {side(first, 0)}");
assert(side(second, 0) == "-32767,", "-2.0 clamps: {side(second, 0)}");
}
// A looping clip of three frames, rendered for seven: 0.25 -> 8192, 0.5 -> 16384,
// -0.5 -> -16384, then again from the start.
fn test_looping_wraps() {
audio::init(8000);
v = audio::play(clip([0.25f, 0.5f, -0.5f]), 1.0, true, -1.0) ?? 0;
out = audio::render(7);
assert(side(out, 0) == "8192,16384,-16384,8192,16384,-16384,8192,", "left: {side(out, 0)}");
assert(audio::playing(v), "a looping voice plays on");
}
// Starting 2 frames in (2 / 8000 s): -0.5, 1.0, then the end.
fn test_start_offset() {
audio::init(8000);
audio::play(clip([0.25f, 0.5f, -0.5f, 1.0f]), 1.0, false, -1.0, 0.00025);
out = audio::render(3);
assert(side(out, 0) == "-16384,32767,0,", "left: {side(out, 0)}");
}
// A 4000 Hz clip at an 8000 Hz output moves half a frame per output frame, interpolating:
// 0, 0.5 (-> 16384), 1.0, then between 1.0 and the silence past the end, 0.5; then done.
fn test_resampling_interpolates() {
audio::init(8000);
c = audio::load_samples([0.0f, 1.0f], 4000) ?? 0;
audio::play(c, 1.0, false, -1.0);
out = audio::render(5);
assert(side(out, 0) == "0,16384,32767,16384,0,", "left: {side(out, 0)}");
}
// A stopped voice's handle acts on nothing, even once its slot plays another voice.
fn test_a_stale_handle_stops_nothing() {
audio::init(8000);
c = clip([0.5f, 0.5f, 0.5f, 0.5f]);
first = audio::play(c, 1.0) ?? 0;
audio::stop(first);
second = audio::play(c, 1.0) ?? 0;
assert(first != second, "a new handle for the reused slot");
audio::stop(first);
assert(audio::playing(second), "stopping the old handle left the new voice playing");
audio::stop_all();
assert(!audio::playing(second), "stop_all stops it");
}
// Volume, pan and position change between renders: 0.5 -> 16384, at volume 0.5 -> 8192, then
// panned hard right; a seek to 0 succeeds, one past the end of a clip that does not loop fails.
fn test_set_volume_pan_and_seek() {
audio::init(8000);
v = audio::play(clip([0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f]), 1.0, false, -1.0) ?? 0;
a = audio::render(1);
audio::set_volume(v, 0.5);
b = audio::render(1);
audio::set_pan(v, 1.0);
c = audio::render(1);
assert(side(a, 0) == "16384,", "full: {side(a, 0)}");
assert(side(b, 0) == "8192,", "half: {side(b, 0)}");
assert(side(c, 0) == "0," && side(c, 1) == "8192,", "panned right: {c}");
assert(audio::seek(v, 0.0), "a seek inside the clip");
assert(!audio::seek(v, 1.0), "a seek past the end of a clip that does not loop");
}
// play_raw plays once at the centre and releases its samples when it ends.
fn test_play_raw() {
audio::init(8000);
v = audio::play_raw([0.25f, 0.75f], 8000, 1.0) ?? 0;
out = audio::render(3);
assert(side(out, 0) == "5792,17377,0,", "left: {side(out, 0)}");
assert(!audio::playing(v), "it ended");
}
// A 16-bit WAV: 16384 / 32768 = 0.5, -0.5, 0, 32767 / 32768 = 0.99997 -> 32766.0 -> 32766.
fn test_wav_mono() {
audio::init(8000);
c = audio::load("mono16.wav") ?? 0;
assert(c > 0, "the WAV loads");
assert(audio::clip_frames(c) == 4 && audio::clip_rate(c) == 8000 && audio::clip_channels(c) == 1,
"4 frames, 8000 Hz, mono");
audio::play(c, 1.0, false, -1.0);
out = audio::render(4);
assert(side(out, 0) == "16384,-16384,0,32766,", "left: {side(out, 0)}");
}
// A stereo clip at the centre passes each side through: (0.5, -0.25), (0.99997, 0).
fn test_wav_stereo_centre() {
audio::init(8000);
c = audio::load("stereo16.wav") ?? 0;
assert(audio::clip_channels(c) == 2, "stereo");
audio::play(c, 1.0);
out = audio::render(2);
assert(side(out, 0) == "16384,32766,", "left: {side(out, 0)}");
assert(side(out, 1) == "-8192,0,", "right: {side(out, 1)}");
}
// A 441 Hz tone at 22050 Hz for 0.25 s (5512 frames), peak 0.0625 (ffmpeg's sine is 1/8 of full
// scale, halved): Vorbis is lossy, so the length and the peak are checked, not the samples.
fn test_ogg() {
if !audio::has_vorbis() { return; }
audio::init(22050);
c = audio::load("tone.ogg") ?? 0;
assert(c > 0, "the OGG loads");
assert(audio::clip_rate(c) == 22050 && audio::clip_channels(c) == 1, "22050 Hz mono");
n = audio::clip_frames(c);
assert(n >= 5500 && n <= 5520, "about 5512 frames, got {n}");
audio::play(c, 1.0, false, -1.0);
out = audio::render(2000);
peak = 0;
i = 0;
while i < len(out) {
s = out[i] ?? 0;
if s > peak { peak = s; }
i += 2;
}
assert(peak > 1850 && peak < 2250, "peak near 2048, got {peak}");
}
fn test_failures_answer_null() {
audio::init(8000);
assert(!audio::load("no-such-file.wav"), "a missing file");
assert(!audio::load_bytes([1 as u8, 2 as u8, 3 as u8]), "bytes that are no clip");
assert(!audio::play(9999, 1.0), "an unknown clip");
assert(!audio::load_samples([], 8000), "no samples");
}