Skip to content

Audio

AudioSourceComponent plays one entity's sound; Audio is the global volume. For the concepts — spatial versus flat, streaming versus decoded — see the Audio guide.

AudioSourceComponent

csharp
public class Enemy : GameEntity
{
    private AudioSourceComponent? m_HitSound;

    protected override void OnCreate()
    {
        m_HitSound = GetComponent<AudioSourceComponent>();
    }

    public void TakeDamage() => m_HitSound?.Play();
}

Every call here is Play-mode only, and each one lazily creates the entity's voice the first time a script touches it. A source with Play On Start off, and one whose clip was only ever assigned in the editor, both just work — the script doesn't need to know which case it's in.

Play()

Starts playing from the beginning.

Stop()

Stops and resets to the start.

Pause()

Stops where it is. Play() resumes from that point.

IsPlaying

Whether the source is currently sounding.

csharp
if (!m_Music.IsPlaying)
    m_Music.Play();

Gain

Volume. 1.0 is the file's own level. Read and write.

csharp
m_Footsteps.Gain = m_Sneaking ? 0.2f : 1.0f;

Pitch

Playback speed and pitch together — 0.5 is an octave down at half speed, 2.0 an octave up at double. Read and write.

csharp
// Slight random pitch stops a repeated sound effect sounding mechanical.
m_HitSound.Pitch = 0.9f + (float)m_Random.NextDouble() * 0.2f;
m_HitSound.Play();

Loop

Turns looping on or off.

Loop is write-only

There's no getter — you can set it but not read it back. If you need to know, keep the value in your own field. (Loop mirrors the underlying audio library, which has no way to report it.)

Audio

Audio.MasterGain

One global multiplier over every sound in the game. Exactly what a settings slider wants.

csharp
Audio.MasterGain = 0.8f;

Also write-only

MasterGain has a setter and no getter, so a volume slider can't ask the engine what it's currently set to. Pair it with a saved setting, which is where the value should live anyway:

csharp
protected override void OnCreate()
{
    Audio.MasterGain = Settings.GetFloat("audio.master", 1.0f);
}

private void OnSliderChanged(float v)
{
    Audio.MasterGain = v;
    Settings.SetFloat("audio.master", v);
    Settings.Save();
}

What isn't scriptable

The clip, Spatial and Play On Start are set in the Properties panel — there's no C# access in 0.1.0. AudioListenerComponent has no façade at all; add the listener in the editor.

There's also no playback-position property and no "finished" callback. To do something when a sound ends, poll IsPlaying from a coroutine:

csharp
private System.Collections.IEnumerator AfterSound(System.Action then)
{
    while (m_Voice!.IsPlaying)
        yield return null;
    then();
}

See also