How do you make Monogame play a sound on a key press and Stop as soon as you stop pressing that key?

Is there any way to make Monogame PLAY a sound whan a key is PRESSED and STOP as soon as the key is RELEASED? I have searched far and wide and NOT been able to find an answer to this question. I hope some enlightened person can help me and all the others who have the same question.

You will need to create a SoundEffectInstance from the SoundEffect in order to be able to stop that particular instance of the sound. Add a field to your class next to where you have the field for the SoundEffect.

SoundEffect mySound;
SoundEffectInstance mySoundInstance;

When you load the sound effect, create an instance of it.

mySound = Content.Load<SoundEffect>("MySound");
mySoundInstance = mySound.CreateInstance();

In your Update, check for the key being held down. If the key is pressed and the sound effect instance is not playing, play it. If the key is not pressed and the sound effect instance is not stopped, stop it.

var keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.Space) && mySoundInstance.State != SoundState.Playing)
    mySoundInstance.Play();
else if (keyboardState.IsKeyUp(Keys.Space) && mySoundInstance.State != SoundState.Stopped)
    mySoundInstance.Stop();
4 Likes

Fabulous! Thank you very much for the prompt reply.