From the ominous ambient sounds of some stygian cave to the familiar din of a crowded marketplace, the proper use of sound can make or break the user experience.
In this short article, I will cover how to set up game audio in Unity. I will begin by adding background music and show you the basics of how the different Audio Components interact.
Unity will automatically add an Audio Listener Component to the Main Camera when you create a new scene. It is important to note that there can only be one Audio Listener per scene. The Audio Listener is responsible for receiving input from Audio Source Components. You can add as many Audio Source Components as you need.
To start playing our in-game music, let’s begin by adding an Audio Source Component to an Empty GameObject.
Next, we have to import a sound file that Unity will use as the Clip for our Audio Source. Unity can interpret a wide variety of audio file formats. In my case, I will be importing an OGG that is my looping soundtrack.
Now that Unity has imported my Clip, I can assign it to my Audio Source in the Inspector.
I also make sure that Play On Awake and Loop are both checked. Selecting these two options will make sure that:
- The music will begin playing at the start of the game.
- The music will loop until the game ends, or I choose to stop it through code.
That is all it takes. As soon as I press the Play button in my editor, the music will be playing in the background. I can adjust the volume manually through the Audio Source Component if I need to.
Like any other Component in Unity, I can use code to manipulate its values. I can also use Audio Effects to enhance my sounds. However, that topic is for another time.
For now, I wanted to show you how easy it is to start setting up a Unity project to play audio files.