Docs / Audio

Audio: emitters

Cached and streaming emitters, clips and file formats, playing, looping, states and events.

Color legend plain property method event

An emitter is a sound source in the world: a position, a list of clips and a chain of effects. Every emitter belongs to the manager that created it and has a name that is unique in it. Names are colored by what they are: a plain property, a method or an event.

Creating emitters

TryAddEmitter creates an emitter under a name and gives it back. It returns false for an empty name or a name that is taken. The new emitter plays its clips straight to the mix, with no effects, until you wire a chain.

if (!audio.TryAddEmitter("door", AudioEmitterTypes.Cached, out var door))
    return; // the name is taken

door.Position = new Vector3(3, 0, -6);
door.TryAddAudio("Content/Audio/door-open.wav");
door.Play();

// later, from anywhere that knows the name
if (audio.TryGetEmitterByName("door", out var found)) found.Play();

// done with it: stops it and disposes its clips and effects
audio.TryRemoveEmitter("door");

EmittersVersion changes whenever an emitter is added or removed, so code that keeps emitter references, such as an ECS component, can tell when to look them up again.

Cached and streaming

The type of an emitter decides where its samples come from:

  • Cached. TryAddAudio decodes the whole clip at once, converts it to the mix format and keeps it in memory. Use it for short sounds that play often, such as footsteps, shots and UI clicks. Starting a cached clip costs nothing.
  • Streaming. The clip stays on disk and is decoded while it plays. Use it for music and long ambiences.

Decoded clips go into one cache shared by the whole process and keyed by path, so every cached emitter, in any manager, that adds the same file shares one copy and only the first one decodes it. Decoding happens on the thread that calls TryAddAudio, so add long cached clips while loading, not in the middle of play. AudioManager.ClearAudioCache() empties the cache: emitters keep the clips they already hold, and the next TryAddAudio of a file decodes it again.

Clips

An emitter holds any number of clips. Each time it starts, from a stop, after it finished or at the start of a new loop, it picks one of them at random, so a footstep emitter with five variations doesn’t repeat one sound over and over.

audio.TryAddEmitter("footsteps", AudioEmitterTypes.Cached, out var steps);

for (var i = 1; i <= 5; i++) steps.TryAddAudio($"Content/Audio/step-{i}.wav");

steps.Play(); // one of the five

TryAddAudio returns false, without throwing, when the path is empty, the emitter already has the file, or the file can’t be opened or decoded. TryRemoveAudio takes a clip out; when it is the clip playing, the emitter picks another one and goes on. ClearAudios stops the emitter and takes them all out.

Supported files:

Format What is read
WAV 8, 16, 24 and 32-bit PCM, and 32-bit float
Ogg Vorbis Any Vorbis stream

Clips can be mono or stereo, at any sample rate: mono is spread to both channels and other rates are resampled to 48 kHz. A clip with more channels is refused by a cached emitter and plays as silence on a streaming one. The format comes from the file’s header, not its extension.

Playing

Play, Pause and Stop control one emitter:

  • Play starts a random clip from the beginning when the emitter is stopped or finished, and resumes it when it is paused. It also cuts short a loop pause.
  • Pause holds the clip where it is. The emitter keeps its place in the mix and sends silence.
  • Stop ends the clip, forgets it and cancels a loop pause. The next Play picks a clip again. A delay effect’s echoes stop with it.

PlayAll, PauseAll and StopAll on the manager do the same for every emitter, and TryPlayEmitter, TryPauseEmitter and TryStopEmitter for one emitter by name.

All three do nothing while the emitter’s chain is broken.

States and events

State tells where the emitter is:

steps.OnStateChanged += emitter =>
{
    if (emitter.State == AudioEmitterPlayingStates.Finished)
        Console.WriteLine($"{emitter.Name} played {emitter.CurrentAudioPath}");
};

The audio thread notices the end of a clip, but the emitter only takes the new state in AudioManager.Update, on the game thread. So OnStateChanged is raised from Update, and right after Play the state still reads what it was until the next update. Rewiring the effect chain changes the state at once, on the thread that rewires.

OnCurrentAudioChanged is raised whenever the emitter takes a clip or lets one go: on Play from a stop, at every new loop, on Stop and when the clip playing is removed. CurrentAudioPath then tells which clip it is, and is empty when there is none. TimeDuration and TimePosition give the length of the current clip and how far it has played.

Looping

A looped emitter starts a new random clip each time one ends. LoopPauseRangeMs adds a silence between them: a random length between its two ends, in milliseconds, drawn anew for every pause. (0, 0), the default, starts the next clip right away.

audio.TryAddEmitter("owl", AudioEmitterTypes.Cached, out var owl);
owl.TryAddAudio("Content/Audio/owl-1.ogg");
owl.TryAddAudio("Content/Audio/owl-2.ogg");
owl.Position = new Vector3(-20, 8, -35);
owl.IsLooped = true;
owl.LoopPauseRangeMs = (4000, 12000); // a call every 4 to 12 seconds
owl.Play();

The end of a clip is handled in AudioManager.Update, so the next clip starts at the first update after the end, not on the exact sample: loops are for ambiences and repeated sounds, not for seamless music loops. The pause is measured by Update too, so it runs on the game’s clock: a paused game that stops calling Update holds the pause as well. During the pause the state is Idle.

Position

Position places the emitter in the world, in the same units as the listener, usually meters. Its effects follow it at once. Without positional effects in its chain, the position changes nothing; the positional sound page adds distance, Doppler and direction.

IAudioEmitter properties

Property Type Description
Name string Read-only. The name the emitter was created under, unique in its manager.
Type AudioEmitterTypes Read-only. Cached or Streaming.
State AudioEmitterPlayingStates Read-only. Where the emitter is: idle, playing, paused, finished, or stopped by a broken chain. Refreshed by AudioManager.Update.
Position Vector3 The emitter’s position in the world. Its positional effects follow it at once.
IsLooped bool Whether a new random clip starts when one ends. Off by default.
LoopPauseRangeMs (int min, int max) The shortest and longest silence between loops, in milliseconds. Negative values are taken as 0, and the two ends are put in order. (0, 0) by default.
CurrentAudioPath string Read-only. The path of the clip the emitter holds, empty when it holds none.
TimeDuration TimeSpan Read-only. The length of the current clip, zero without one.
TimePosition TimeSpan Read-only. How far the current clip has played. A time position effect can also set it.
EffectLoopSend EmitterSendEffect Read-only. Where the effect chain starts: the samples of the clip. See effect chains.
EffectLoopReturn EmitterReturnEffect Read-only. Where the effect chain ends: what goes to the mix.

IAudioEmitter events

Event Handler Raised when
OnStateChanged (IAudioEmitter sender) State changes. From AudioManager.Update on the game thread, or from the thread that rewires the chain.
OnCurrentAudioChanged (IAudioEmitter sender) The emitter takes a clip or lets one go: on play, at every loop, on stop, and when the clip playing is removed.

IAudioEmitter methods

Method Description
TryAddAudio(string path) Adds a WAV or Ogg Vorbis clip. A cached emitter decodes it now. false for an empty path, a file the emitter has already, or one that can’t be opened or decoded.
TryRemoveAudio(string path) Takes a clip out and disposes it. When it is the clip playing, another random clip starts. false when the emitter doesn’t have it.
ClearAudios() Stops the emitter and takes every clip out.
Play() Starts a random clip when stopped or finished, resumes when paused. Cuts short a loop pause.
Pause() Holds a playing clip where it is.
Stop() Ends the clip and forgets it, cancels a loop pause and clears the echoes of delay effects.
Update(float elapsedSeconds) Refreshes the state, runs the loop pause and measures Doppler speeds. AudioManager.Update calls it for every emitter; don’t call it yourself as well.
Dispose() Stops the emitter and disposes its clips and effects. Remove emitters through the manager instead, which disposes them.

The effect methods of an emitter are on the effect chains page.

AudioManager emitter properties

Property Type Description
EmittersVersion int Read-only. Changes whenever emitters are added, removed or cleared, so cached emitter references can be looked up again.

AudioManager emitter methods

Method Description
TryAddEmitter(string name, AudioEmitterTypes type, out IAudioEmitter emitter) Creates an emitter under a name, starting from the current listener pose. false for an empty name or one that is taken.
TryGetEmitterByName(string name, out IAudioEmitter audioEmitter) Finds an emitter by its name.
TryRemoveEmitter(string name) Takes an emitter out of the mix and disposes it.
ClearEmitters() Removes and disposes every emitter.
TryAddAudioToEmitter(string emitterName, string pathToAudio) TryAddAudio on the emitter of that name.
TryRemoveAudioFromEmitter(string emitterName, string pathToAudio) TryRemoveAudio on the emitter of that name.
TryClearEmitterAudios(string emitterName) ClearAudios on the emitter of that name.
TryPlayEmitter(string name) Play on the emitter of that name.
TryPauseEmitter(string name) Pause on the emitter of that name.
TryStopEmitter(string name) Stop on the emitter of that name.
PlayAll() Play on every emitter.
PauseAll() Pause on every emitter, for a pause menu.
StopAll() Stop on every emitter.
ClearAudioCache() Static. Empties the cache of decoded clips. Emitters keep the clips they hold; the next TryAddAudio of a file decodes it again.

The Try methods by name return false when there is no emitter of that name. Otherwise they return what the emitter’s own Try method returns, or true for the methods that return nothing.

AudioEmitterTypes

Value Meaning
Cached Clips are decoded once into memory, shared by every cached emitter. For short, frequent sounds.
Streaming Clips are decoded from disk while they play. For music and long ambiences.

AudioEmitterPlayingStates

Value Meaning
Idle No clip is playing: the emitter is new or stopped, or waits in a loop pause.
Playing A clip is playing.
Paused A clip is held by Pause.
Finished A clip of an emitter that doesn’t loop played to its end. Play starts a new one.
EffectLoopDisconnected The effect chain doesn’t reach the return, so the emitter is stopped and ignores play, pause and stop.

PlayingStates

The state of the current clip on the audio thread, from which AudioManager.Update works out State. It is public, in the BorrowedTorch.Audio.SampleProviders namespace, but no public member returns it: read State instead.

Value Meaning
Idle No clip is playing.
Playing The clip is playing.
Paused The clip is held.
EofReached The clip has played to its end; the next update starts a loop or finishes the emitter.