# How to play a sound only one time in XNA?

I'm using a sound when a key is pressed, like a fire. But despite that I'm pressing the key for just a short moment, the sound is playing so many times. I guess it's because of the Update method that updates it all 60 times per second.

Is there a way to play the sound only one time, until I press the next time? I also have the same problems with sprites when they hit the border a short "bang" sound is played, but it dosen't sounds like it should do! I guess it playes to many times!?

Help id preciated to solve this! Thanks!

if (keyboardState.IsKeyDown(Keys.Space))
{
code play sound and activate a sprite
}


What you need to do is check if this is the FIRST time the key has been pressed. Remember that the game updates 60 times per second (that's about once every 16.6ms!), so when you press the button, it's unlikely you're going to have it held down only for 1 frame. The way you get around this is to keep the previous keyboard state as well as the current keyboard state. You then compare them to see if this is the first frame the key has been pressed and execute your code only if that is true.

So, at the top of the class, add these two field variables:

KeyboardState _currentKeyboardState;
KeyboardState _previousKeyboardState;


Then, your Update will look like this:

public void Update(GameTime gameTime) {
//Update the current keyboard state at the beginning of Update
_currentKeyboardState = Keyboard.GetState();

//Do all your update stuff here

//Last line in the update statement:
//Set the previous keyboard state to the current one.
// On the next frame, this will be equal to the keyboard state on THIS frame.
_previousKeyboardState = _currentKeyboardState;
}


So, now that you have those two things, you can check if the keyboard has been newly pressed by checking both states like so:

if (_currentKeyboardState.IsKeyDown(Keys.Space) && //Currently pressed
_previousKeyboardState.IsKeyUp(Keys.Space)) { //Was Up on the last frame
//If the Space key is currently pressed and was not pressed on the
// last frame, play a sound
}


That's the basics of how it works. Let me know if you have any questions.

On a side note, I have a more in-depth explanation on my blog relating specifically to checking the different states (Up, Click, Hold, Release) using the mouse if you're interested.

• Great! Glad to help. :) Jul 12 '12 at 19:05