- Home /
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!!
Can this be updated for 2019? the code is now obsolete
Answer by FunctionR · Nov 17, 2013 at 08:37 PM
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.
This will get the audio to play, but is there any way to mute that audio source when I press escape? Thank you so much for your help!
Your answer
Follow this Question
Related Questions
Audio Source will not "unmute" after toggling? 2 Answers
Can anyone help me invert this simple script? 2 Answers
How to STOP music when loading a SPECIFIC SCENE? 3 Answers
play music on key press 1 Answer
Audio plays when i click F 1 Answer