AudioSystem: API practice
Use this skill when you need to quickly select the correct AudioSystem method and apply it without regressions :)
Freshness reference: git blame with cutoff 2024-02-19.
What to download
references/fresh-pattern-catalog.md- API registry with recommendations.references/rejected-snippets.md- legacy/TODO/dangerous scenarios.references/docs-context.md- how to use docs safely.
Quick API selection
- We need a sound “for everyone around the source”:
PlayPvs(sound, uid/coords, params). - We need a sound “for a specific recipient”:
PlayEntity/PlayGlobal/PlayStatic(..., recipient, ...). - We need predicted UX without duplicates:
PlayPredicted(sound, source/coords, user, params). - We need runtime flow control:
SetState,SetPlaybackPosition,Stop,IsPlaying. - You need a map/grid special sound:
SetMapAudio,SetGridAudio. - You need a reverb/filter effect:
CreateEffect + CreateAuxiliary + SetEffectPreset + SetEffect + SetAuxiliary. - Need volume/tone/range setting:
AudioParams.With*and/orSetVolume/SetGain.
API by group
1) Resolve and utilities
ResolveSound(SoundSpecifier)- pins a specific track from the collection.GetAudioPath(ResolvedSoundSpecifier?)- gets the real path.GetAudioLength(...)- duration for seek/timers.GetAudioDistance(length)- takes into account Z-offset.GainToVolume/VolumeToGain- translation between gain and dB.
2) Playback API (basis)
PlayGlobal(...)- non-positional sound.PlayEntity(...)- the sound follows the entity.PlayStatic(...)- sound in fixed coordinates.PlayPvs(...)- shorthand for the PVS audience.- All groups have overloads under:
SoundSpecifier/ResolvedSoundSpecifier, Filter, ICommonSession, EntityUid recipient.
3) Predicted API
PlayPredicted(sound, source, user, params).PlayPredicted(sound, coords, user, params).PlayLocal(...)- local predicted-alias.
4) Control of an already playing thread
SetState(stream, Playing/Paused/Stopped).SetPlaybackPosition(stream, seconds).SetVolume(stream, dB)/SetGain(stream, gain).Stop(stream).IsPlaying(stream).
5) Spatial map/grid modes
SetMapAudio(audioEntity)- map-wide sound.SetGridAudio(audioEntity)— grid center, tuned distance,NoOcclusion.
6) Stream API (client runtime)
PlayGlobal(AudioStream, ...).PlayEntity(AudioStream, ...).PlayStatic(AudioStream, ...).LoadStream<T>(entity, stream)— loading source from stream-type.
7) OpenAL Effects API (EFX)
CreateEffect()- creates an effect entity.CreateAuxiliary()- creates an auxiliary slot entity.SetEffectPreset(effect, presetProtoOrReverb)- applies a set of parameters.SetEffect(aux, effect)- attaches effect to slot.SetAuxiliary(audio, aux)- connects the slot to the source.- Shortcut:
SetEffect(audioUid, audioComp, presetId).
Patterns
- For player interactions, always pass
userand usePlayPredicted. - For long music/stateful SFX, store stream
EntityUid?and control viaSetState/Stop. - For wobbly/large objects (shuttles, platforms) do
PlayPvs -> SetGridAudio. - For map events (timers, global phases) do
PlayPvs -> SetMapAudio. - For rich-acoustics, first assemble an EFX chain, then connect it to the active stream.
- For one-off sounds with variation, use
AudioParams.WithVariation(...). - For “quieter/louder in runtime” prefer
SetVolume; for linear coefficients -SetGain.
Anti-patterns
- Pull
PlayPvsin the predicted code wherePlayPredictedis needed. - Use old TODO zones as a template for the new API.
- Rely on server
LoadStream<T>as a work contract. - Add effects until the real source is ready, without taking into account the life cycle.
- Mix map/grid semantics manually instead of
SetMapAudio/SetGridAudio. - Ignore the
AudioStatestate and try to “cure” the flow only by deleting the entity.
OpenAL effects: practical minimum
- Reverb parameters live in
AudioEffectComponent(Density,Decay*,Echo*,Modulation*,HF/LF*). AudioAuxiliaryComponentholds the link to the effect.AudioComponent.Auxiliaryconnects slot to a specific source.- Occlusion in EFX mode uses lowpass; without EFX it degrades into gain-fallback.
Code examples
1) Predicted sound from interaction
// The user already hears locally; the server will exclude it from the repeat event.
_audio.PlayPredicted(ent.Comp.UseSound, ent.Owner, args.User, AudioParams.Default.WithVariation(0.25f));
2) Station music/event only for the right audience
// The server itself creates a station filter + PVS and sends out a network event.
var spec = _audio.ResolveSound(sound);
_globalSound.PlayGlobalOnStation(sourceUid, spec, AudioParams.Default.WithVolume(-8f));
3) Ping-aware seek for synchronous playback
// Compensation for network delay when rewinding the current track.
var offset = session.Channel.Ping * 1.5f / 1000f;
Audio.SetPlaybackPosition(streamUid, requestedTime + offset);
4) Grid audio for FTL phase
// We tie the shuttle sound to grid semantics, and not to a local point.
var audio = _audio.PlayPvs(startupSound, shuttleUid);
_audio.SetGridAudio(audio);
5) Complete EFX chain
// We created an effect + slot, applied a preset and connected it to a specific audio.
var effect = _audio.CreateEffect();
var aux = _audio.CreateAuxiliary();
_audio.SetEffectPreset(effect.Entity, effect.Component, presetPrototype);
_audio.SetEffect(aux.Entity, aux.Component, effect.Entity);
_audio.SetAuxiliary(soundUid, soundComp, aux.Entity);
6) Thread state management
// Pause/resume/stop - via state API.
Audio.SetState(streamUid, AudioState.Paused);
Audio.SetState(streamUid, AudioState.Playing);
Audio.SetState(streamUid, AudioState.Stopped);
Rule of application
- By default, select
Fresh-Usemethods from the reference directory. - Use
Legacy-Compatonly when clearly necessary and with tests. - Do not use
Risk/TODOas a reference point for a new API design. - Check any audio API refactoring for prediction, PVS and EFX fallback at the same time.
Keep the API layer predictable: the right overload and the right recipient are more important than a “short” call 😅