Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

c# - How to play file from Library by MediaElement?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...