LibraryPlaying and Controlling Audio

Playing and Controlling Audio

Learn about Playing and Controlling Audio as part of Game Development with Unity and C#

Mastering Audio Playback and Control in Unity

Sound is a critical element in game development, immersing players and providing vital feedback. This module will guide you through the fundamental concepts and practical implementation of playing and controlling audio within the Unity game engine using C#.

The Audio Source Component

In Unity, audio playback is primarily managed by the <b>Audio Source</b> component. This component is attached to a GameObject and acts as the source of sound in your scene. It requires an <b>Audio Clip</b> to play.

The Audio Source component is the heart of audio playback in Unity.

Every sound you hear in your Unity game originates from an Audio Source component attached to a GameObject. This component dictates which sound file (Audio Clip) plays, how it plays, and its spatial properties.

The Audio Source component has numerous properties that control playback. Key among these are:

  • <b>AudioClip</b>: The sound file to be played.
  • <b>Play On Awake</b>: If checked, the audio will play automatically when the GameObject becomes active.
  • <b>Loop</b>: If checked, the audio will repeat indefinitely.
  • <b>Volume</b>: Controls the loudness of the audio, ranging from 0 (silent) to 1 (full volume).
  • <b>Spatial Blend</b>: Determines whether the sound is 2D (heard at full volume regardless of listener position) or 3D (volume decreases with distance from the listener).

Playing Audio with C#

You can programmatically control audio playback using C# scripts. This allows for dynamic sound events triggered by player actions or game state changes.

What is the primary Unity component responsible for playing audio?

The Audio Source component.

To play audio via script, you'll need a reference to the Audio Source component. You can get this reference by:

  1. Attaching a script to the same GameObject as the Audio Source.
  2. Using
    code
    GetComponent()
    to retrieve the component.
  3. Calling the
    code
    Play()
    method on the Audio Source.

Here's a basic C# script to play an audio clip. The script requires an Audio Source component attached to the same GameObject. You'll also need to assign an Audio Clip to the audioClipToPlay variable in the Inspector. The PlaySoundEffect() method can be called from other scripts or Unity events.

📚

Text-based content

Library pages focus on text content

csharp
using UnityEngine;
public class AudioPlayer : MonoBehaviour
{
public AudioClip audioClipToPlay;
private AudioSource audioSource;
void Awake()
{
audioSource = GetComponent();
if (audioSource == null)
{
Debug.LogError("AudioSource component not found on this GameObject.");
}
}
public void PlaySoundEffect()
{
if (audioSource != null && audioClipToPlay != null)
{
audioSource.PlayOneShot(audioClipToPlay);
}
else
{
Debug.LogWarning("AudioSource or AudioClip is not assigned.");
}
}
// Example of playing a clip directly without PlayOneShot
public void PlayClip()
{
if (audioSource != null && audioClipToPlay != null)
{
audioSource.clip = audioClipToPlay;
audioSource.Play();
}
}
}

Controlling Audio Playback

Beyond simply playing sounds, you can control various aspects of audio playback, such as volume, pitch, and stopping playback.

Fine-tune audio playback with scriptable properties.

You can dynamically adjust an Audio Source's volume, pitch, and even stop playback entirely using C# methods, allowing for nuanced audio experiences.

Key methods and properties for control include:

  • <b>audioSource.Stop()</b>: Stops the currently playing audio clip.
  • <b>audioSource.Pause()</b>: Pauses the audio playback.
  • <b>audioSource.UnPause()</b>: Resumes paused audio playback.
  • <b>audioSource.volume</b>: Set or get the volume of the Audio Source (0.0 to 1.0).
  • <b>audioSource.pitch</b>: Set or get the pitch of the audio (1.0 is normal pitch, higher values increase pitch, lower values decrease it).
  • <b>audioSource.time</b>: Set or get the current playback position in seconds.

Using PlayOneShot() is often preferred for sound effects as it allows multiple instances of the same sound to play concurrently without interrupting each other, unlike Play() which will stop and restart the clip if called again.

Spatial Audio and 3D Sound

Unity's 3D audio capabilities allow sounds to originate from specific points in 3D space, creating a more immersive experience. The <b>Spatial Blend</b> property on the Audio Source is crucial here.

Spatial Blend ValueBehaviorListener Interaction
0 (2D)Sound is heard at full volume regardless of listener position.Volume is constant.
1 (3D)Sound volume attenuates (decreases) with distance from the listener.Volume changes based on distance and direction.
0.5 (Mid)A blend between 2D and 3D audio.Partial attenuation based on distance.

The <b>Min Distance</b> and <b>Max Distance</b> properties further control how the volume of a 3D sound changes with distance. Within the Min Distance, the sound is at its full volume. Between Min and Max Distance, the volume gradually fades. Beyond Max Distance, the sound is inaudible.

What Audio Source property controls whether a sound is 2D or 3D?

Spatial Blend.

Learning Resources

Unity Manual: Audio Overview(documentation)

The official Unity documentation provides a comprehensive overview of Unity's audio system, including the Audio Source component and its properties.

Unity Learn: Introduction to Audio(tutorial)

A guided learning path on Unity Learn covering the basics of audio in Unity, from importing clips to implementing sound effects.

Unity Scripting API: AudioSource(documentation)

Detailed reference for the AudioSource class, including all its methods and properties for programmatic control.

Unity Blog: Making Games Sound Great(blog)

Articles from the Unity blog often feature tips and techniques for improving audio design in games.

YouTube: Unity 3D Audio Tutorial(video)

A practical video tutorial demonstrating how to set up and control audio sources in Unity.

GDC Vault: Game Audio Techniques(video)

A collection of talks from the Game Developers Conference covering advanced game audio design and implementation strategies.

Unity Answers: Playing Sound Effects(documentation)

A common question and answer on Unity Answers demonstrating how to play sound effects using C# scripts.

Wikipedia: Sound Design(wikipedia)

Provides a general understanding of sound design principles and its role in various media, including games.

Unity Learn: Audio Mixer(tutorial)

Learn how to use Unity's Audio Mixer to control and process audio effects for your game.

Unity Blog: Spatial Audio in Unity(blog)

An article detailing the implementation and benefits of spatial audio for creating immersive game soundscapes.