Using audio in Unity
A quick guide about how to start using audio in Unity
Objective: Set up a scene in a space shooter game to start using background music with Unity.
In order to show how to start using audio with Unity, we’ll implement background music in a space shooter game.
Listening to audio
As you can see in the next image, an Audio Listener component is attached to the main camera of the scene by default. This component provides a way to receive input from any Audio Source component and then play its sound trough the speakers. There can only be one Audio Listener component per scene.
If you want to know more about the Audio Listener component you can visit the Unity docs:
Switch to Scripting The Audio Listener acts as a microphone-like device. It receives input from any given in the scene…
Now, in order to input audio, let’s create an empty gameobject that will represent the audio manager of the whole scene. Then, as the background music source, create another empty gameobject as its child:
Select the background gameobject and add an Audio Source component in the inspector:
If you want to know more about the Audio Source component you can visit the Unity docs:
class in UnityEngine / Inherits from: Behaviour / Implemented in: UnityEngine.AudioModule Suggest a change Thank you…
Finally, in order to play the music in the game, let’s drag the file from the project folders into the Audio Clip property of the Audio Source component. And, as it’s the background music, let’s make sure that Play on Awake and Loop properties are enabled:
Now every time we run the game, the background music will start playing and it won’t stop once it’s over thanks to the Loop property enabled in the Audio Source component.
And that’s it, you can start using audio in Unity! :D. I’ll see you in the next post, where I’ll be showing how to play sound effects in Unity.