UWP MediaElement not play music

1

I am implementing a music player that plays local music files.

I got this error message as my MediaElement failed:

MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED : HRESULT - 0x80070005

How should I fix it? This is my MediaElement.

<MediaElement
    x:Name="MediaPlayer"
    Grid.Column="1"
    AutoPlay="False"
    IsLooping="False"
    MediaEnded="MediaPlayer_MediaEnded"
    MediaFailed="MediaPlayer_MediaFailed"
    Volume="50" />

I have tried 3 ways of playing the audio but none of them worked for me.

var file = await StorageFile.GetFileFromPathAsync(music.Path);
MediaPlayer.Source = new Uri(music.Path, UriKind.Absolute);
//MediaPlayer.SetSource(await file.OpenReadAsync(), file.ContentType);
//MediaPlayer.SetSource(await file.OpenAsync(FileAccessMode.Read), file.ContentType);

The music.Path (containing path and music filename) is correct because I can load the Album Cover thumbnail. By the way the music file is located at somewhere in the Desktop not in the Assets folder.

I think there is a similar question here: Mediaelement in Windows 8 Metro App

But I don't understand why one of the answer is opening a picker. I don't think that would be my solution as I am just playing all the music files under a local folder.

---Update---

I notice that the MediaElement plays music correctly when I am playing an Asset music. So I guess there should be a workaround for playing local music files?

c#
xaml
uwp
uwp-xaml
asked on Stack Overflow Aug 9, 2019 by (unknown user) • edited Aug 25, 2019 by (unknown user)

1 Answer

1

I have found the solution. It's pretty simple.

The key part is to have a StorageFolder object (in my code it is CurrentMusicFolder) containing the music file to be played. For example, I need to play this music file: "C:\MusicFolder\Music.mp3". So I need to do:

StorageFolder CurrentMusicFolder = await StorageFolder.GetFolderFromPathAsync("C:\MusicFolder");
var file = await CurrentMusicFolder.GetFileAsync("Music.mp3");
MediaPlayer.SetSource(await file.OpenAsync(FileAccessMode.Read), file.ContentType);
MediaPlayer.Play();

Note that the path of music is "Music.mp3" instead of "C:\MusicFolder\Music.mp3". You cannot have things like "C:\" in the music path.

answered on Stack Overflow Aug 10, 2019 by (unknown user)

User contributions licensed under CC BY-SA 3.0