Search code examples
c#audioxnawindows-phone-8soundeffect

InvalidOperationException occured when trying to load wma file as SoundEffect using Microsoft.Xna.Framework


I get Invalid Operation Exception when trying to load WMA file (no DRM) as Sound Effect. My code:

    public void LoadSound(String SoundFilePath, out SoundEffect Sound)
    {

        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);
        }
        catch (NullReferenceException)
        {
            // Display an error message
            MessageBox.Show("Couldn't load sound " + SoundFilePath);
        }
    }

The error occured at this line Sound = SoundEffect.FromStream(SoundFileInfo.Stream)

I can load WAV files without problem though. I prefer not to convert the WMA file into WAV because the original WMA file size is just 352KB but when converted to a WAV file its size increased to 1788KB!


Solution

  • You cannot use wma or mp3 sounds within SoundEffects. Try this approach that works just fine:

    using Microsoft.Xna.Framework.Media;
    ...
    Song s = Song.FromUri("sound name", new Uri(@"Resources/Alarms/Alarm01.wma", UriKind.Relative));
    MediaPlayer.Play(s);
    

    Also don't forget to reference Microsoft.Xna.Framework library.