Audio Manager

TGorillaAudioManager is the backend independent heart of the audio building block. It is an abstract TFmxObject — you never instantiate it directly, you drop one of its two implementations on the form and program against the base class. Everything built on top of the audio stack (playlist, text-to-speech, speech-to-text) only knows this base class, which is what makes the driver exchangeable.

Table of Contents

Overview

Class Unit Purpose
TGorillaAudioManager Gorilla.Audio.Manager Abstract manager, the API everything else uses
TGorillaSoundItem Gorilla.Audio.Manager Abstract single sound, a TCollectionItem
TGorillaChannelItem Gorilla.Audio.Manager Abstract playback channel
TGorillaAudioEffectItem Gorilla.Audio.Manager Abstract effect slot
TGorillaLegacyAudioManager Gorilla.Audio.Manager Old TMediaPlayer based manager, thread driven
TGorillaFMODAudioManager Gorilla.Audio.FMOD FMOD implementation
TGorillaOpenALManager Gorilla.Audio.OpenAL OpenAL implementation

Creating a Manager

Both implementations are design-time components, so the usual way is to drop them onto the form. At runtime they are created like any other FMX component:

uses
  Gorilla.Audio.Manager, Gorilla.Audio.OpenAL;

var LAudio : TGorillaAudioManager;
begin
  LAudio := TGorillaOpenALManager.Create(Self);
  TGorillaOpenALManager(LAudio).Parent := GorillaViewport1;

From here on the code can stay on the TGorillaAudioManager type. Swapping the driver later is a one line change.

Sound Items

A TGorillaSoundItem is one loaded piece of audio. It is a collection item, so sounds can be pre-configured at design-time through the Object Inspector and are owned and released by their manager.

Member Description
FileName Path of the audio file
PlaybackPosition Current position in milliseconds (read-only)
PlaybackLength Total length in milliseconds (read-only)
IsPlaying() True while audible
Play() / Pause() / Resume() / Stop() Playback control
LoadFromStream(AStream) Fills an item created with CreateSoundItem()

On top of that every item carries the backend independent 3D interface:

Method Description
Supports3DAudio() True when the driver can place this sound in space
Set3DAudio(AEnabled) Switches positional playback on — before loading the data
SetWorldPosition(APosition) Moves the sound in world space
Set3DDistance(AMin, AMax) Distance range the sound is attenuated in
SetPlaybackVolume(AVolume) Gain, 0.0 silent … 1.0 unchanged
SetPlaybackPitch(APitch) Pitch, 1.0 unchanged, 2.0 one octave up

The base class implements these as no-ops, so a driver only overrides what it really supports. This is the interface the text-to-speech module uses to make a character's voice come out of the character.

Loading Sounds

var LSound : TGorillaSoundItem;
begin
  // from a file
  LSound := LAudio.LoadSoundItemFromFile('sounds/explosion.wav');

  // from a stream - read completely into memory
  LSound := LAudio.LoadSoundItemFromStream(LFileStream);

  // from a memory stream - can be streamed continuously
  LSound := LAudio.LoadSoundItemFromStream(LMemoryStream);

  // look a sound up again
  LSound := LAudio.GetSoundItemByFilename('sounds/explosion.wav');

  // drop everything
  LAudio.ClearSounds();
end;

The LoadSoundFrom...() overloads without Item in their name do the same but return nothing — use them when the sound is only ever addressed by index.

Two Step Creation

Some settings are evaluated while the audio data is created and cannot be changed afterwards — FMOD decides about 3D handling when the sound is created, for example. For those cases the item is created empty, configured, and filled afterwards:

var LSound : TGorillaSoundItem;
begin
  LSound := LAudio.CreateSoundItem('guard_voice');
  if Assigned(LSound) then
  begin
    LSound.Set3DAudio(true);
    LSound.Set3DDistance(1.0, 40.0);
    LSound.LoadFromStream(LWaveStream);
  end
  else
    // driver does not support it, fall back
    LSound := LAudio.LoadSoundItemFromStream(LWaveStream);
end;

CreateSoundItem() returns nil when the driver cannot do the two step creation, so a caller always needs the fallback shown above.

Playback

LAudio.PlaySound(LSound);   // by item
LAudio.PlaySound(0);        // by index

LSound.Play();
LSound.Pause();
LSound.Resume();
LSound.Stop();

if LSound.IsPlaying then
  ShowMessage(Format('%d / %d ms',
    [LSound.PlaybackPosition, LSound.PlaybackLength]));

LAudio.StopAllChannels();
LAudio.ClearAllChannels();

3D Audio

Positional audio needs two things: sounds that have a position, and a listener that has one too. The sound side is the item interface shown above, the listener side is driver specific — FMOD offers ListenerTarget to follow a TControl3D automatically, OpenAL offers ListenerPosition, ListenerOrientation and ListenerVelocity. See FMOD Driver and OpenAL Driver.

LSound.Set3DAudio(true);
LSound.Set3DDistance(2.0, 50.0);       // full volume up to 2 units, silent at 50
LSound.SetWorldPosition(Torch.AbsolutePosition.Point);
LSound.SetPlaybackVolume(0.8);

Keep the listener in sync every frame, otherwise the panning lags behind the camera.

Channels

A channel is a playing instance of a sound. The base class exposes only the two global operations, because the two drivers model channels quite differently:

Method Description
StopAllChannels() Stops everything currently audible
ClearAllChannels() Stops and releases all channels

For categories (music, SFX, voice) use the driver specific grouping: FMOD channel groups or OpenAL channels.

The Update Loop

procedure TForm1.GorillaViewport1Render(Sender : TObject; ...);
begin
  FAudio.Update();
end;

Update() refills streaming buffers, retires finished channels and applies listener changes. FMOD can do this on its own — AutoUpdate with AutoUpdateInterval (33 ms by default) runs an internal thread. When you drive the manager yourself, switch AutoUpdate off so the work happens at a defined point in your frame.

Events

Event Fired when
OnUpdate Update() was called; synchronized with the main thread when the auto-update thread triggered it
OnListenerUpdated The listener position or orientation changed

Legacy Audio Manager

TGorillaLegacyAudioManager is a TThread descendant that keeps one FMX TMediaPlayer per audio file. It is simple, needs no external library at all, and is not built for performance. A global instance called AudioManager is created by the unit.

uses Gorilla.Audio.Manager;

// cache files first, that is much faster than loading them one by one
AudioManager.BeginCaching();
AudioManager.Add(1, 'sounds/explosion.wav');
AudioManager.Add(2, 'sounds/background.mp3');
AudioManager.Add(3, 'sounds/footstep.wav', 0.5);   // 50% volume
AudioManager.EndCaching();

AudioManager.Play(1);                                    // once
AudioManager.Play(2, TGorillaAudioMode.Loop, 0.3);       // looped, 30% volume

AudioManager.Pause(2);    // pause / resume toggle
AudioManager.Stop(1);
AudioManager.PauseAll();
AudioManager.StopAll();

AudioManager.Mute := true;
Property Default Description
LoopCheckInterval 100 Interval in ms at which finished loops are restarted
QueueTimeout 250 Time in ms the worker waits for a queue event
Mute False Mutes every cached file at once

Limitations worth knowing before you pick it:

  • One TMediaPlayer per file — memory use grows quickly with the number of sounds
  • No 3D audio, no effects, no channel grouping
  • The first media player has to be created in the main thread, which is why the unit stores an empty.mp3 in the temp directory during initialization; if that fails, playback is not possible
  • Startup slows down noticeably, because caching loads every file completely

Use it for tools, prototypes and menu clicks. Everything else belongs on FMOD or OpenAL.

Best Practices

  • Program against TGorillaAudioManager, not against the concrete driver — it keeps the driver exchangeable and lets the speech modules work either way
  • Call Update() once per frame, or leave FMOD's AutoUpdate on
  • Configure 3D settings before the audio data is loaded (CreateSoundItem())
  • Use channel groups (FMOD) or channels (OpenAL) for master volume per category
  • Release sounds when a scene is left, otherwise handles accumulate
  • Prefer streaming for music and long ambiences, full loading for short effects

See Also

API Reference

Related Topics