How to play file from Library by MediaElement?

2019-01-28 21:26发布

I can play files only from application storage, but, I have to play file from Library or another source. The I try to:

        var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("C:\\Users\\admin\\Music\\line.mp3"));
        var stream = await storageFile.OpenAsync(FileAccessMode.Read);

        mediaElement.SetSource(stream, storageFile.ContentType);

        mediaElement.Play();

It's gives exception: "An exception of type 'System.ArgumentException' occurred in Polar.exe but was not handled in user code. Additional information: Value does not fall within the expected range."

I tried mediaElement.Source() to, but element is not playing the sound. No exception, no anything.

I think it's foolish problem, but I can't find solution. What I am doing wrong?

1条回答
Bombasti
2楼-- · 2019-01-28 22:02

If you want to play audio files from library, then you need to use KnownFolders. GetFileFromApplicationUriAsync won't work.

var storageFile = await KnownFolders.MusicLibrary.GetFileAsync("line.mp3");
var stream = await storageFile.OpenAsync(FileAccessMode.Read);
mediaElement.SetSource(stream, storageFile.ContentType);
mediaElement.Play();

If you want enumerate all the media file or all the folders then use this.

var AllStorageFiles = await KnownFolders.MusicLibrary.GetFilesAsync();
var AllStorageFolders = await KnownFolders.MusicLibrary.GetFoldersAsync();
查看更多
登录 后发表回答