2

Does anyone have a working (tested) example of code to play an audio file from isolated storage. The code I currently have, which doesn't throw an exception or make any sound, is:

        MediaElement ME = new MediaElement();
        ME.AutoPlay = false;
        IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
        ME.SetSource(ISF.OpenFile("foo.wav", FileMode.Open));
        ME.Play();

I've tried this using a number of different audio formats, encoded using Expression, but I always have the same problem.

Also, I'd quite like an example using the file browser to load the song from a file stream, however this is less important and the Isolated Storage example could easily be converted.

I've checked, and if I embed the file in the application, it plays fine. The problem is I want users to be able to load their own songs into the application, which will then be stored in and played from isolated storage.

Finally, as with the example, I'd rather be doing this in C# code, rather than XAML.

ForbesLindesay
  • 10,482
  • 3
  • 47
  • 74
  • Did you check the `CurrentState` property afterwards? Did you try hooking a handler to the `MediaFailed` event? – Ben Voigt Dec 02 '10 at 05:38
  • Have you tried opening a text or image file to make sure that you've got that bit right? – ChrisF Dec 02 '10 at 11:21
  • 1
    The current state was going straight to paused. It seems that the play method won't work until after the file is loaded (worked when I put it in a separate event handler). Setting AutoPlay to true works fine. – ForbesLindesay Dec 02 '10 at 11:33
  • 1
    You should add that as an answer and accept it (in a couple of days)> It will help anyone else who has the same problem. – ChrisF Dec 02 '10 at 12:59
  • I'm experiencing a similar problem. Would be grateful if you posted your solution as an answer. – Stephen Dec 02 '10 at 14:43

1 Answers1

1
  1. You can't have the Play command in the same method as the SetSource command since the file will be opened asynchronously. By setting AutoPlay to true (which is also the defualt). You ensure that it will play as soon as it's loaded.

    MediaElement ME = new MediaElement();
    ME.AutoPlay = true;
    IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
    ME.SetSource(ISF.OpenFile("foo.wma", FileMode.Open));
    
  2. Silvelright doesn't natively support wav files, so to play wav files you need to download http://code.msdn.microsoft.com/wavmss, then use the following code.

    MediaElement ME = new MediaElement();
    ME.AutoPlay = true;
    IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
    ME.SetSource(new WaveMediaStreamSource(ISF.OpenFile("foo.wav", FileMode.Open)));
    

    Although not ideal, you can use the file extensions to detect when a wav file is being played and use the second code sample only in this case.

ForbesLindesay
  • 10,482
  • 3
  • 47
  • 74