Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Animation and Audio

Audio in Unity - Sources, Listeners and Mixers

Add sound to a Unity game with AudioSource, AudioListener, 3D spatial audio, PlayOneShot and the AudioMixer, including decibel and distance falloff math you can run.

Sound is half of the feel of a game. A jump with no whoosh and a coin with no chime feel flat, and music sets the mood of a level. Unity's audio has three main parts: AudioClips (the sound files), AudioSources (components that play them) and one AudioListener (the "ears", usually on the main camera). On top of that, the AudioMixer lets you control groups of sounds, such as music, effects and voices.

This lesson explains each part, how to play sounds from code, how 3D sound fades with distance, and how volume sliders map to decibels. The Unity C# is read-only; the math runs as plain C# stand-ins.

Clips, sources and the listener

  • Import .wav, .ogg, .mp3 or .aif files into the project; each becomes an AudioClip. In the clip's import settings choose a Load Type: Decompress On Load for short effects (fast to play, uses memory), Compressed In Memory for medium sounds, Streaming for long music (little memory, a bit of CPU). Tick Force To Mono for effects that will be positioned in 3D.
  • An AudioSource plays one clip at a time. Fields to know: AudioClip, Output (a mixer group), Play On Awake, Loop, Volume, Pitch and Spatial Blend.
  • The scene needs exactly one active AudioListener; the main camera has it by default. Two listeners cause a warning and one of them is ignored.

Playing sounds from code

C#
using UnityEngine;

public class Coin : MonoBehaviour
{
    [SerializeField] AudioClip pickup;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (!other.CompareTag("Player")) return;
        AudioSource.PlayClipAtPoint(pickup, transform.position, 0.8f);
        Destroy(gameObject);
    }
}

PlayClipAtPoint creates a temporary source, which is convenient when the object is about to be destroyed but allocates each time. For frequent sounds keep an AudioSource and use PlayOneShot:

C#
[SerializeField] AudioSource sfx;
[SerializeField] AudioClip[] footsteps;

public void Footstep()
{
    sfx.pitch = Random.Range(0.92f, 1.08f);              // tiny variation avoids a machine-gun feel
    sfx.PlayOneShot(footsteps[Random.Range(0, footsteps.Length)], 0.6f);
}

Play() restarts the source's own clip and cuts off the previous one; PlayOneShot layers sounds over each other, so rapid hits overlap naturally. Use Stop(), Pause() and UnPause() for control and isPlaying to check. PlayDelayed and PlayScheduled(AudioSettings.dspTime + x) give sample-accurate timing, useful for a rhythm game or seamless music loops.

3D sound and distance falloff

Spatial Blend 0 is a 2D sound (music, UI clicks) heard at the same volume everywhere; 1 is fully 3D, with volume and left-right panning depending on where the source is relative to the listener. For 3D sources the Volume Rolloff curve (Logarithmic, Linear or Custom) and Min/Max Distance shape how quickly the sound fades.

Within Min Distance the sound is at full volume. Beyond that, logarithmic rolloff follows roughly an inverse-distance law, so the volume halves each time the distance doubles, and the source goes silent past Max Distance.

C# Stand-in: distance rolloff

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choose logarithmic for realistic world sounds and linear for sounds that should vanish cleanly at a limit. The Doppler effect, reverb zones and the Spread angle add more realism but are rarely needed at first.

The Audio Mixer

Create one with Assets > Create > Audio Mixer and open it from Window > Audio > Audio Mixer. Inside, build groups: a Master group with children Music, SFX and Voice. Assign each AudioSource's Output to a group. Now you can:

  • adjust each group's volume and add effects (low-pass filter, reverb, compressor, ducking);
  • create snapshots (for example Normal and Underwater or Paused) and blend between them with snapshot.TransitionTo(0.5f);
  • expose parameters (right-click Volume, Expose) and set them from a script, which is how an options menu works.

Mixer volume is in decibels (dB), from -80 (silent) to +20. A UI slider usually runs 0 to 1, and the conversion is logarithmic:

C#
using UnityEngine;
using UnityEngine.Audio;

public class VolumeSettings : MonoBehaviour
{
    [SerializeField] AudioMixer mixer;

    public void SetMusicVolume(float slider01)
    {
        float dB = Mathf.Log10(Mathf.Max(slider01, 0.0001f)) * 20f;
        mixer.SetFloat("MusicVolume", dB);
    }
}
C# Stand-in: slider to decibels and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because the ear hears loudness logarithmically, a linear dB mapping would feel wrong: most of the useful range sits at the top of the slider. Always convert as above.

Music and good habits

  • Play music from a persistent object with DontDestroyOnLoad so it survives scene loads, or use an additive audio scene.
  • Fade with a coroutine on the mixer parameter or AudioSource.volume rather than cutting.
  • Avoid dozens of simultaneous voices: AudioSource's Priority and the project's Max Real Voices limit decide who gets dropped. Throttle repeated sounds (for example one hit sound per 50 ms).
  • Keep effect clips small and mono; stream music; test with the Profiler's Audio module (see Profiler and optimization).
  • Browsers and some mobile platforms block audio until the player interacts; WebGL builds start sound after the first click.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many active AudioListeners should a scene normally have?

    Only one listener is used; the main camera carries it by default.
  2. 2. Which call layers a sound over others without cutting the current one?

    PlayOneShot starts the clip in addition to whatever the source is already playing.
  3. 3. Why convert a 0-1 slider to decibels with Log10 before setting a mixer parameter?

    dB is a log scale, so a linear mapping would feel wrong and 0 would be minus infinity.
  4. 4. Which Spatial Blend value gives a purely 2D sound such as UI music?

    0 means no 3D attenuation or panning; 1 is fully spatial.

Summary

  • AudioClips are played by AudioSources and heard by one AudioListener.
  • Use PlayOneShot for overlapping effects, random pitch for variety, and the right Load Type for each clip.
  • Spatial Blend, Min/Max Distance and the rolloff curve control 3D sound.
  • The AudioMixer groups sounds, exposes parameters (in dB) and supports snapshots and effects.

Next: Timeline and Cinemachine