Inserting audio: environmental sfx, background music, sound events

Let's try now to add some ambiance, music in the background,  and some sound effects. We downloaded the sounds from freesound.org or opengameart.org. All the audio clips collected for the book are mostly free from copyright or under the creative commons license with some rights reserved for some soundtrack and sounds.

Open the Chapter2-3-4/Audio folder. Drag the Volcano Lava Fire  and  Low Wind audio clips into the scene.

Then, import the book's code, Soundtrack.unitypackage. After importing, drag the file into the Assets/Soundtrack directory and DarkWinds into the scene. On both GameObjects Audio Source components, set the Loop checkbox to true.

Now choose the Warrior2D player GameObject and manually add an AudioSource component to it. Activate the loop on this too, uncheck the Play On Awake option, because we don't want this sound effect to start automatically when the scene is loaded, and select the Chapter2-3-4/Audio/hardrunfootsteps file. Instead, we want to loop the audio when the character is running. To implement it, add these lines of code before the end of the Move() method in the PlatformerCharacter2D:

if (m_Anim.GetBool("Ground") && Math.Abs(move)>0.5f) 
{ 
    if(!GetComponent<AudioSource>().isPlaying) GetComponent<AudioSource>().Play(); 
} 
else GetComponent<AudioSource>().Stop();

To avoid calling the GetComponent<AudioSource>() API method each frame we are going to cache the value of this component in the  Start() method, so because we did remove it, we will add it in again and add a new private variable of the AudioSource type to store the object:

m_audioSource = GetComponent<AudioSource>();

We will also change the code we wrote earlier into this:

if (m_Anim.GetBool("Ground") && Math.Abs(move)>0.5f) 
{ 
    if(!m_audioSource.isPlaying) m_audioSource.Play(); 
} 
else m_audioSource.Stop();

Press Play and test the game; you should hear the background music, the ambient sound, and, when the player runs, the footsteps audio playing. There is a little issue with sound volume, as we can barely hear the footsteps, and the ambient sound is way too loud for the music soundtrack. Change the overall volume of these two audio components, setting the DarkWave soundtrack to 0.5 and the ambient sound to 0.25.  It should sound a lot better now!

Another easy enhancement to apply would be to tweak the pitch (hence, the speed) of the footstep sound. Try to set a value between 1.1 and 1.25 (which means slightly faster and higher pitched) to hear footsteps in sync with the steps taken in the character animation while running.