Pausing and playing audio on key press?

Hello All,

I am currently attempting to toggle an audio source when I press the Escape key. I want to pause and play the music when I enter and leave the pause menu. If anybody could help me out with this, I would really appreciate it. Thanks so much!!

Check for the input of the Escape key. I assume you have a pointer to your AudioSource

bool isPlaying = false;

Make sure that isPlaying is declared as an instance variable not inside the function that checks for input.

if(Input.GetKey(KeyCode.Esc)
{
   isPlaying = !isPlaying;

   if(isPlaying)
     audio.Stop();

   else
     audio.Play();
}

The basic idea is to have a Boolean value that gets changed every time the user hits the escape key. If isPlaying was true then it will get set to false. Then we check the value of isPlaying if it is true then we just stop playing, else we play the audio.

Think of it this way. If sound is playing then the user has hit the ESC button already.

API reference to Audio