Audio with miniaudio
Audio is the subsystem with the hardest real-time deadline in the engine. The graphics thread may drop a frame and nobody notices; if the audio callback is late by a few milliseconds the speaker clicks. So audio code follows strict rules: the mixer runs on its own thread, called by the OS whenever the device needs the next small block of samples (typically 5–20 ms), and that callback must never block, lock a contended mutex, allocate or load a file.
An engine's audio layer has three parts:
| Part | Job |
|---|---|
| Device / backend | talks to WASAPI, Core Audio, ALSA/PulseAudio/PipeWire, AAudio, Web Audio |
| Mixer | sums the active voices into one buffer, applying volume, pan, pitch, effects |
| Game-facing API | "play this sound here", groups (music, SFX, voice), 3D positions, limits on how many voices play at once |
miniaudio (David Reid, public domain or MIT-0) covers all three in a single C file with no dependencies. Add miniaudio.c to your build, or define MINIAUDIO_IMPLEMENTATION before including miniaudio.h in exactly one source file.
A mixer, modelled
Mixing is addition. Each voice produces samples; the mixer multiplies them by the voice's gain, splits them between left and right with a pan law, and adds them into the output. A constant-power pan law (left = cos θ, right = sin θ, with θ from 0 to π/2) keeps a sound equally loud as it moves across the stereo field; a plain linear split makes it dip in the middle.
The model also shows voice limiting: with a budget of three real voices, the lowest-priority sound is made virtual. A virtual voice keeps its playback position advancing but is not mixed, so it can come back seamlessly if a slot frees up.
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
struct Voice {
std::string name;
double freq, gain, pan; // pan: -1 = left, 0 = centre, +1 = right
int priority;
long cursor = 0; // samples played so far
bool virtualVoice = false;
};
int main() {
const double sampleRate = 48000, pi = 3.14159265358979;
const int maxRealVoices = 3, blockSize = 6;
std::vector<Voice> voices = {
{"music", 220, 0.30, 0.0, 10},
{"footstep", 880, 0.50, -0.6, 2},
{"explosion", 55, 0.90, 0.4, 8},
{"bird", 1760, 0.20, 1.0, 1},
};
// voice limiting: keep the highest priorities real
std::vector<Voice*> order;
for (auto& v : voices) order.push_back(&v);
std::stable_sort(order.begin(), order.end(), [](Voice* a, Voice* b) { return a->priority > b->priority; });
for (int i = 0; i < int(order.size()); i++) order[i]->virtualVoice = i >= maxRealVoices;
for (auto& v : voices) std::cout << std::left << std::setw(10) << v.name << (v.virtualVoice ? "virtual" : "real") << "\n";
// mix one block (what the audio callback does)
std::vector<float> out(blockSize * 2, 0.0f); // interleaved L R L R ...
for (auto& v : voices) {
double theta = (v.pan + 1) * pi / 4; // 0 .. pi/2
double gl = v.gain * std::cos(theta), gr = v.gain * std::sin(theta);
for (int i = 0; i < blockSize; i++, v.cursor++) {
if (v.virtualVoice) continue; // still advances its cursor
double s = std::sin(2 * pi * v.freq * double(v.cursor) / sampleRate);
out[2 * i] += float(s * gl);
out[2 * i + 1] += float(s * gr);
}
}
int clipped = 0;
std::cout << std::fixed << std::setprecision(4);
for (int i = 0; i < blockSize; i++) {
for (int c = 0; c < 2; c++) {
float& x = out[2 * i + c];
if (x > 1.0f || x < -1.0f) { clipped++; x = std::clamp(x, -1.0f, 1.0f); }
}
std::cout << "frame " << i << ": L " << std::showpos << out[2 * i] << " R " << out[2 * i + 1] << std::noshowpos << "\n";
}
std::cout << "bird cursor " << voices[3].cursor << ", clipped samples " << clipped << "\n";
std::cout << "centre pan gain each side: " << std::cos(pi / 4) << " (constant power), 0.5000 (linear)\n";
}music real
footstep real
explosion real
bird virtual
frame 0: L +0.0000 R +0.0000
frame 1: L +0.0637 R +0.0296
frame 2: L +0.1267 R +0.0590
frame 3: L +0.1882 R +0.0880
frame 4: L +0.2476 R +0.1162
frame 5: L +0.3041 R +0.1435
bird cursor 6, clipped samples 0
centre pan gain each side: 0.7071 (constant power), 0.5000 (linear)
The bird is virtual but its cursor still moved six samples, so if the footstep ends, the bird resumes at the right point in its sound rather than restarting. Real mixers also apply a limiter or soft clipper on the master bus instead of hard clamping, and smooth gain changes over a few milliseconds so volume changes don't click.
miniaudio's high-level engine
ma_engine gives you a device, a mixer, a resource manager that decodes WAV, FLAC and MP3 out of the box (other formats through pluggable decoders), sound groups, and 3D spatialisation:
#include "miniaudio.h"
ma_engine engine;
if (ma_engine_init(NULL, &engine) != MA_SUCCESS) { /* no audio device: keep running silently */ }
ma_engine_play_sound(&engine, "sfx/click.wav", NULL); // fire and forget, for UI sounds
ma_sound_group sfx, music;
ma_sound_group_init(&engine, 0, NULL, &sfx);
ma_sound_group_init(&engine, 0, NULL, &music);
ma_sound_group_set_volume(&music, 0.6f); // options-menu sliders map to groups
ma_sound theme;
ma_sound_init_from_file(&engine, "music/theme.flac", MA_SOUND_FLAG_STREAM, &music, NULL, &theme);
ma_sound_set_looping(&theme, MA_TRUE);
ma_sound_start(&theme);
ma_sound shot; // decoded fully into memory: short and frequent
ma_sound_init_from_file(&engine, "sfx/shot.wav", MA_SOUND_FLAG_DECODE, &sfx, NULL, &shot);
ma_sound_set_position(&shot, 4.0f, 0.0f, -2.0f); // 3D position in world units
ma_sound_set_pitch(&shot, 1.05f);
ma_sound_start(&shot);
// each frame, from the camera / listener entity:
ma_engine_listener_set_position(&engine, 0, camPos.x, camPos.y, camPos.z);
ma_engine_listener_set_direction(&engine, 0, camForward.x, camForward.y, camForward.z);
// shutdown
ma_sound_uninit(&shot);
ma_sound_uninit(&theme);
ma_sound_group_uninit(&sfx);
ma_sound_group_uninit(&music);
ma_engine_uninit(&engine);Use MA_SOUND_FLAG_STREAM for long music and ambience (decoded a little at a time) and MA_SOUND_FLAG_DECODE for short effects that play often. Add MA_SOUND_FLAG_ASYNC to load without stalling the game thread. To play the same effect several times at once, create several ma_sound objects from the same file (ma_sound_init_copy); the resource manager shares the decoded data.
For full control (your own mixer, as in the model), use the low-level ma_device API with a dataCallback, which hands you the output buffer to fill.
Note: Ogg Vorbis and Opus are not built into miniaudio's core decoders; plug in a custom decoder (the repository's
extrasfolder has some) or ship WAV/FLAC/MP3. Check the README of the version you use.
Engine integration tips
- Treat missing audio hardware as normal. A server, a CI machine or a laptop with no output device should run the game silently, not crash.
- Give each sound an event name (
"weapon/shotgun/fire") in game code and map it to files, variations, volume and pitch randomisation in data. Designers then tune audio without touching code, which is what FMOD Studio and Wwise do on a larger scale. - Drive the listener from the active camera, and 3D sounds from entity transforms, in one system after the transform update.
- Pause groups, not individual sounds, when the game pauses (keep UI sounds playing).
| Middleware | When |
|---|---|
| miniaudio | small to mid-sized games, full source control, no licence fees |
| SoLoud | another free engine-level library with filters and speech synthesis |
| FMOD Studio, Audiokinetic Wwise | when a sound designer authors interactive audio in a dedicated tool; check current licence terms |
Test yourself
Why must the audio callback never load a file or wait on a busy mutex?
- Files can't be read from threads
- It has a hard real-time deadline; if it is late, the output underruns and the listener hears clicks or dropouts
- miniaudio forbids it
- It runs before the game loop starts
What is the point of a constant-power pan law?
- It saves CPU
- A sound keeps the same perceived loudness as it moves between left and right
- It makes sounds louder in the centre
- It is required for 3D audio
What does a virtual voice do?
- Plays at half volume
- Keeps its playback position advancing without being mixed, so it can resume seamlessly
- Is deleted immediately
- Plays on a different device