Search code examples
c#wpfaudiowindows-phone-8wpf-controls

Forcing MediaElement to Release Stream after playback


I am creating an audio recorder control, with playback functionality.

I use the media element to play the recorded audio like this:

using (var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
{
    using (System.IO.Stream stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(filePath, System.IO.FileMode.Open, storage))
    {
        player.SetSource(stream);
    }
}

The problem i am facing is that when I use media element to play the recorded audio. The Stream is locked to the media element. I cannot overwrite the file or even play it again as the SetSource() method throws an exception.

Is there a way to force the media element to release the stream?


Solution

  • Based on @Sheridan answer this it what I came up with that works.

    Whenever MediaElement is stopped using Stop() function set the Source Property to null like this:

    ResetMediaElement()
    {
        mediaElement.Stop();
        mediaElement.Source = null;
    }
    

    This will close the stream attached to the media element, so that the related resource can be used somewhere else.