Audio
Game code plays sound by name. An audio event asset groups one or more clips under a name, your code posts that name, and the engine mixes the result to the output device. Scripts never open files or hold a device.
The audio bricks split this work. org.mass4.turian.audio holds the events, sources, listener, bus mixer and the session that plays them. org.mass4.turian.audio.miniaudio supplies the playback device and the WAV, MP3 and FLAC decoders, and it is what makes a game audible. org.mass4.turian.audio.studio adds the View → Audio Mixer panel to Studio. Install the first two in a game that should make sound. Without the miniaudio brick, an interactive game runs with a silent device.
Setting up
Add org.mass4.turian.audio and org.mass4.turian.audio.miniaudio to the project, from Project → Bricks… or in Bricks/manifest.json (see Bricks). Then create an Audio Settings asset under Settings, only if you want to change its defaults:
| Setting | Default | Meaning |
|---|---|---|
SampleRate |
48000 | Output frames per second. |
BufferFrames |
512 | Requested device period in frames. |
DeviceName |
empty | Exact playback device name. Empty selects the system default. |
MaxVirtualVoices |
64 | Voices that can play at once. Extra voices are stolen by priority and distance. |
MaxStreams |
4 | Streamed events that can play at once. |
StreamBufferFrames |
32768 | Frames buffered ahead for each streamed voice. |
Mixer |
none | An Audio Mixer asset. Empty uses the default buses. |
The device opens when the first event is prepared, not when the game starts.
Importing clips
Drop a .wav, .mp3 or .flac file into the asset browser. Turian imports it as an AudioClip, and the clip is decoded when an event that uses it is prepared. Ogg Vorbis files are not accepted.
Audio events
Create an Audio Event asset (Audio/Audio Event) and fill in:
| Field | Default | Meaning |
|---|---|---|
EventName |
empty | The name your code posts. Give every event its own name. |
Clips |
empty | The variations. Each post plays the next one in turn. |
Bus |
SFX |
The mixer bus the event plays through. |
Volume, Pitch |
1 | Multipliers for every voice of the event. |
Loop |
off | Repeat until stopped. |
Spatial |
off | Pan and attenuate by distance from the listener. |
MinDistance, MaxDistance |
1, 100 | Distances in meters where attenuation starts and ends. |
Priority |
128 | Which voices survive when there are too many. |
Stream |
off | Decode while playing instead of holding the sound in memory. |
Streamed events accept mono and stereo clips only.
Playing sounds
There are two ways to play an event.
- An
AudioSourcecomponent (Audio/Source) on a node. Assign itsEvent, and turn onPlayOnStartif it should play as the scene starts. ItsVolumeandPitchscale its voices, and it stops them when it is disabled. The source follows the node's position, so moving the node moves the sound. - Your own script, which prepares an event on start and posts it when something happens.
The second way looks like this. It is a reduction of AudioDemoMotion.cs in example-15-audio:
using Microsoft.Extensions.DependencyInjection;
using Silk.NET.Input;
using Turian.Audio;
public sealed class Clicker : Component
{
IInputSource? input;
IAudioService? audio;
string clickEventName = string.Empty;
public DataAssetReference<AudioEvent>? ClickEvent { get; set; }
public override void OnStart()
{
input = Services?.GetService<IInputSource>();
audio = Services?.GetService<IAudioService>();
if (audio is not null)
{
clickEventName = audio.Prepare(ClickEvent ?? throw new InvalidOperationException("Assign the click event before starting the scene."));
}
}
public override void OnUpdate(float deltaTime)
{
if (input?.WasMouseButtonPressed(MouseButton.Left) == true)
{
audio?.Post(clickEventName, Id, new AudioParameterSet());
}
}
public override void OnDisable() => audio?.StopAll(Id);
}
Three rules make this work:
- Prepare in
OnStart.Prepareloads the clips and returns the event's name. Post only that returned name. Preparing duringOnUpdateis not allowed, and posting an event that was not prepared throws. - Post from the main thread. Audio commands are queued by the game thread and mixed on the audio thread.
- Stop by owner.
Posttakes an owner (hereId), soStopAll(owner)andPause(owner)affect only that component's voices.
AudioSource has the same operations: Post, StopAll(fadeOutSeconds) and Pause(paused). A fade-out gives the voices a short release instead of a click.
Pausing
Pause(true) holds every voice of an owner where it is, and Pause(false) resumes it. Game pause menus usually pause the gameplay sounds and leave the music or menu sounds playing, which is what a mixer snapshot is for; see below.
When the application goes into the background, the engine releases the device and reopens it when the application returns, so the game does not keep an audio device while it is hidden.
The listener
An AudioListener (Audio/Listener) publishes its node's global pose each frame. Spatial events are panned and attenuated relative to it. Add it to the camera's node, so that sound follows what the player sees. A node can hold only one listener.
Volume
Volumes are linear amplitudes: 1 is unchanged, 0 is silent, and 0.5 is about 6 dB quieter. Each voice multiplies the event's Volume, the source's Volume and the gain of its mixer bus. Two calls set levels for the whole session:
IAudioService.SetMasterVolume(volume)scales the output. Zero mutes without stopping any voice, so unmuting resumes the sounds where they were.- The mixer's bus faders, described below, control one group of sounds at a time.
A settings screen usually binds sliders to the mixer, not to the master volume alone. example-16-audio-showcase shows a MasterVolumeBinding that binds one bus to a settings variable and reflects changes made elsewhere.
The mixer
An Audio Mixer asset (Audio/Audio Mixer) defines the buses, their effect chains and the snapshots. Select it in Audio Settings under Mixer. Without one, the session has five buses: Master, Music, SFX, Voice and UI.
- Each bus has a name and a parent. The first bus is
Masterand has no parent. Names are case-sensitive, andAudioEvent.Busroutes events by name. - Each bus runs its effects in order before its fader, and sends its output to its parent. The built-in effects are low-pass and high-pass filters, stereo delay, reverb, compressor, limiter and distortion.
- A snapshot sets the gain and mute of several buses at once, and can change effect wet amounts. A transition crossfades to it over a number of seconds.
- Ducking lowers one bus while a detector bus is loud, for example to lower the music while a voice line plays.
Limits: 64 buses, 16 effects per bus, 64 snapshots and 64 MiB of effect state per mixer. Your own effects can be registered through IAudioEffectFactory. Their kernels run in the audio callback, so they must not allocate or block.
Effects and routing are compiled when the session starts, so edit the mixer while Play is stopped. Faders, mutes and snapshots can change during Play.
Game code controls the mixer through IAudioMixerService:
var mixer = Services?.GetService<IAudioMixerService>();
mixer?.SetBusVolume("Music", 0.5f);
mixer?.SetBusMute("SFX", false);
mixer?.TransitionTo("Underwater", 0.7f);
var meter = mixer?.GetMeter("Music");
Each call returns false when the command queue is full. The state changes only when the call is accepted, so retry on the next frame if it matters. GetBus(name) returns the requested volume, mute and solo, and GetMeter(name) returns the post-fader peak and RMS levels of the bus.
Studio adds the View → Audio Mixer panel, available during Play. It has a decibel fader, mute and solo, stereo meters and snapshot audition for every bus. Its changes apply to the running session only, and restarting Play restores the authored mixer.
Devices
- The device is named by
AudioSettings.DeviceName, which must match a device name exactly. Leave it empty for the system default. - If the device cannot start,
PreparethrowsInvalidOperationExceptionwith a message that says so. Catch it if your game can run without sound, or show a message. - Servers and other non-interactive hosts use a silent service. They allocate no device, decoder or effect state, and an event can be prepared and posted without making any sound.
SampleRateandBufferFramesare read when the device opens, so a change applies from the next session.
Streams
Resident events decode their clips when prepared and hold the samples in memory. Set Stream on an event to decode while it plays instead. A streamed event keeps StreamBufferFrames ahead for each voice, and at most MaxStreams streamed voices can play at once. Use streams for music and long ambience, and resident events for short effects that repeat often.
Diagnostics
IAudioService.Statistics reports the active voices, the active streams and the number of stream underruns. An underrun means a streamed voice ran out of decoded audio. A larger StreamBufferFrames gives the decoder more time ahead of playback.
The editor's audio validator checks code and scenes for two common mistakes before the game runs:
AUD0001means aPostcannot be traced to an event that was prepared inOnStart. Prepare the assigned event at startup and post the returned name.AUD0002means a scene file is incomplete, so the audio event wiring in it could not be checked.
Example projects
example-15-audio is a small scene with a click sound, an ambient loop and a spatial source that moves around the listener. Its AudioDemoMotion.cs is the script shown above.
example-16-audio-showcase has four stages. They play streamed MP3 and FLAC music, place sounds relative to the camera, bind master volume and mute to the settings, and audition the mixer with underwater and pause snapshots, a Voice cue that ducks the music, and a reverberant SFX cue. Its Assets/Audio folder holds the mixer asset, ShowcaseMixer.dataasset, and the audio it uses, all synthesized for the example.
Limitations
- Ogg Vorbis is not supported.
- Spatial sound is panning with distance attenuation. There is no HRTF and no occlusion.
Next steps
- Physics — collisions are a common source of sound events.
- Components — the lifecycle that
OnStart,OnUpdateandOnDisablebelong to. - Input — reading the keys and buttons that trigger sounds.
- Bricks — installing the audio bricks.