# XNA - how to prevent a sound from looping

So in XNA I have this code: Variables:

SoundEffect optionSelected;


In the LoadContent() method:

optionSelected = Content.Load<SoundEffect>("gameSounds\\selectOption");


In the Update() method:

optionSelected.Play();


So when it comes time for the sound to play it never stops looping. I want to hear it only once. How to achieve that? Thanks in advance!

• – MichaelHouse Sep 12 '13 at 21:01
• This question is C++ related, I need c# xna help. – PowerUser Sep 13 '13 at 20:26
• The logic is the same for either language. The first answer is somewhat specific to C++, but the other answers work just as well for C#. – MichaelHouse Sep 13 '13 at 20:29

Well if you are calling Play() every time the update loop runs it will play each time the game updates. However ignoring that to stop it looping you'd do

optionSelected = Content.Load<SoundEffect>("gameSounds\\selectOption");
optionSelected.IsLooped=false;


Hope that helps

EDIT: From the comment thread the solution would be to add a keypress event listener and call Play() when the desired key is pressed.

• Uh... IsLooped is a member of SoundEffectInstance and not SoundEffect. The Play method on the latter is just a convenience method for fire-and-forget sounds which, naturally, don't support looping. – Andrew Russell Sep 13 '13 at 2:13
• Yep this did not work. Any other suggestions? – PowerUser Sep 13 '13 at 10:35
• How are you calling it from your update loop? you might want it after an if statement such as if(isOptionClicked==true) {optionSelected.Play(); isOptionClicked=false;}. Or stick it somewhere else – user1646196 Sep 13 '13 at 10:44
• OK, I used a bool but now when it comes time for the sound to play, well it doesn't play. Reply would be really nice! – PowerUser Sep 13 '13 at 16:25
• You have to set the boolean to true at some point. Are you sure you want the sound in the update loop. If this is for an option being selected then I'm assuming a button is clicked or something of that ilk. If so you could add an event handler to whatever is triggering the sound so when it's clicked it plays instead of keeping it in the update loop – user1646196 Sep 14 '13 at 10:38