I have a button that will control a sound effect. When the button is clicked, the sound should start to play. If you click it while the sound is still playing, it should stop the sound. If you click it after the sound stopped playing by itself, the sound should start playing again.
I have tried this, but I am using the SoundState method incorrectly, as it doesn’t work:
public void playGenericSound(string fileName)
{
if (playingSound.State != SoundState.Playing)
{
using (var stream = TitleContainer.OpenStream(fileName))
{
var effect = SoundEffect.FromStream(stream);
playingSound = effect.CreateInstance();
FrameworkDispatcher.Update();
playingSound.Play();
}
}
else
{
playingSound.Stop();
}
}
Any ideas?
Many thanks in advance!
Will.
For XNA app:
In the update() method check your sound effect’s playingSound.State field and if the playback has stopped, play another one.
For Silverlight:
This part is a bit tricky since SoundEffectInstance was designed as a part of XNA. For example, you can make your own loop using a Timer and inside the event handler, add your state checking logic.
A second idea is to use a timer with it’s interval set to the duration of your playing Sound and add a flag like bool isPlaying. When you play it for the first time set the isPlaying flag to true and start the timer. In the timer handler set the isPlaying flag to false. Each time your press the button check the isPlaying flag. In other words, make your own play-state logic.
You can combine these methods.