Lesson 49 +10 XP

AudioSource & AudioListener

AudioSource & AudioListener

To play sound effects or music in Unity, you need to understand how the audio engine simulates sound waves in virtual space.

Core Components

The audio system works like a microphone and a speaker:

  • Audio Listener: Acts as the microphone. It listens to sound sources and outputs them to the player's physical speakers. There must be exactly one active Audio Listener in a scene (typically attached to the Main Camera).
  • Audio Source: Acts as the speaker. It plays an Audio Clip asset in the scene.

Playing Audio via Code

You can control when sound effects play using C#:

public class Door : MonoBehaviour
{
    private AudioSource source;
    public AudioClip openSound;

    void Start()
    {
        source = GetComponent<AudioSource>();
    }

    public void Open()
    {
        // Play the assigned sound clip once
        source.PlayOneShot(openSound);
    }
}

3D Spatial Audio

To configure an Audio Source to play 3D positional audio:

  1. Select the Audio Source component in the Inspector.
  2. Find the Spatial Blend slider.
  3. Slide the value from 0 (2D) to 1 (3D).
  • 2D Sound: Plays at constant volume everywhere, regardless of where the object is (useful for background music or UI clicks).
  • 3D Sound: Volume attenuates (fades) as the Audio Listener moves away from the Audio Source. The sound also pans left and right depending on the listener's orientation, creating immersive spatial depth.

TL;DR

  • The Audio Listener functions as the ear; only one should be active in a scene.
  • The Audio Source plays an assigned Audio Clip.
  • Use source.PlayOneShot to play sound effects without interrupting current audio.
  • Slide Spatial Blend to 1 to enable 3D spatial volume attenuation.