How to use audio in Unity

· 3 min read
How to use audio in Unity

Audio and sound are important component in the Unity. This article will show how to add audio or sound in your project.

The audio format:

Up until 2020, the most latest Unity (2019.3.x) supports aif, wav, mp3, ogg.

To have sound in the project:

First we need to make sure we have the Audio Listener component is attached to the main camera. Be noticed here, main camera is the most common place we play the sound. You can also add this component to any other global game object in your project, such as GameManager. (Refers to this article if you want to know a bit more details on this).

audio listener

Notice: we can have only one Audio Listener in a game.

Then add an Audio Source component to the game object you want play sound. The real situation can be different in your project. If it is a background music, you can just add Audio Source to the main camera.

And that is it, you are now have the background sound in the project. However, most of cases require us to play a certain sound in a specific occasion, such as a player hit with a weapon. So we can write some code to achieve this.

Use code to play sound

First create an empty Game Object AudioManager in the hierarchy, this will help to organize your project code in a cleaner way.

Then create an AudioManagerScript component under AudioManager with the following code:

using UnityEngine;
using UnityEngine.Audio;
using System;


[System.Serializable]
public class Sound {

	public string name;
	public AudioClip clip;

	[Range(0f, 1f)]
	public float volume;

	[Range(0.1f, 3f)]
	public float pitch;

    public bool isLoop;

	[HideInInspector]
	public AudioSource source;
}

public class AudioManagerScript : MonoBehaviour {

    public Sound[] sounds;

    void Awake() {
        foreach (Sound s in sounds) {
            s.source = gameObject.AddComponent<AudioSource>();
            s.source.clip = s.clip;
            s.source.volume = s.volume;
            s.source.pitch = s.pitch;
            s.source.loop = s.isLoop;
        }
    }


    public void Play(string name) {
        Sound s = Array.Find(sounds, sound => sound.name == name);
        Debug.Log("play sound "+name);
        if (s == null) {
            Debug.LogWarning("Can't find the sound "+name);
            return;
        }
        s.source.Play();
    }
}

Back to the AudioManager game object in the hierarchy, add the sound clip:

You can add more audio clips by changing the Sound size. So the sound can be played in the code:

FindObjectOfType<AudioManagerScript>().Play("Hit");

Reference

How to use audio in Unity
Audio and sound are important component in the Unity. This article will show howto add audio or sound in your project. The audio format:Up until 2020, the most latest Unity (2019.3.x) supports aif, wav, mp3, ogg. To have sound in the project:First we need to make sure we have the Audio Listener…