Search code examples
c#windows-phone-7xna-4.0soundeffect

How to check if sound effect is playing (Looping a BG Song)


Here is the setup I am rolling at the moment. Given this, how can I tell when the _BGMusic SoundEfect is over? I am running a game loop that cycles a few times a second and I ultimately want to loop this song.

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;

    SoundEffect _BGMUSIC;

    public Page1() {
     ...

     LoadSound("sfx/piano.wav", out _BGMUSIC);
     ...
    }

    private void LoadSound(String SoundFilePath, out SoundEffect Sound) {
        // For error checking, assume we'll fail to load the file.
        Sound = null;
        try {
            // Holds informations about a file stream.
            StreamResourceInfo SoundFileInfo =
                    App.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));
            // Create the SoundEffect from the Stream
            Sound = SoundEffect.FromStream(SoundFileInfo.Stream);
            FrameworkDispatcher.Update();
        } catch (NullReferenceException) {
            // Display an error message
            MessageBox.Show("Couldn't load sound " + SoundFilePath);
        }
    }

Solution

  • Alright so the answer to this question is actually very simple and outlined in Microsoft's MSDN page very nicely (for once).

    To implement it with what I have up above currently you need to do the following.

    Create a global SoundEffectInstance

     SoundEffectInstance _BGMUSICINSTANCE;
    

    In my example I initialize the SoundEffect in my main method so underneath it I want to initialize the SoundEffectInstance.

    _BGMUSICINSTANCE = _BGMUSIC.CreateInstance();
    

    Now that the instance is loaded and ready we can set its loop property to true. You can do this also in the main method or wherever you want. It's a global

     _BGMUSICINSTANCE.IsLooped = true;
    

    Finally play the song

     _BGMUSICINSTANCE.Play();
    

    Reference page http://msdn.microsoft.com/en-us/library/dd940203(v=xnagamestudio.31).aspx