Jnr Jnr - 1 year ago 126
C# Question

Can one use the Source property of a MediaElement to play content?

I'm trying to play songs from a local machine by using the directory path to the song.

MediaElement.Source = new Uri(@"D:\Music\Artist\Album\Song.mp3", UriKind.Absolute);

Is this even possible to get to work or can Windows 8 apps only use URI schemes like mss-appx: to access package data?

When I try and run the code I get a message on the MediaElement control "Invalid Source"

Answer Source

Windows Store apps do not have full access to the file system. They can directly access (by path) only limited locations (i.e. their install and applicationdata folders).

The MediaElement can load items from paths it can directly access, but this is not generally useful since these locations have URIs (ms-appx: and ms-appdata:) which will target the right location regardless of what the actual Path is.

Typically songs are in the Music library, which the MediaElement cannot directly access. It can get brokered access through the MusicLibrary capability, but that doesn't allow access by path. The app will need to get to the file through the KnownFolders object:

private async void Button_Click(object sender, RoutedEventArgs e)
    StorageFolder musicLib = Windows.Storage.KnownFolders.MusicLibrary;
    StorageFile song = await musicLib.GetFileAsync(@"Artist\Album\Song.mp3");
    var stream = await song.OpenReadAsync();
    me.SetSource(stream, stream.ContentType);

If the song isn't in a library that can be permitted by capability then the user will need to grant permission through a FolderPicker or such. The user can pick the root of the music location and the app can cache that with the Windows.Storage.AccessCache classes so the user doesn't need to pick the folder multiple times or individually pick files.

I discuss this in more detail in my blog entry Skip the path: stick to the StorageFile

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download