I am trying to play a song from my listview in UWP. However when I click on the song (listview item) to play it I get the follwing error:
System.IO.FileNotFoundException: 'The system cannot find the file specified. (Exception from HRESULT: 0x80070002)'
This is my code:
private async Task InitFolderAsync()
{
StorageFolder musicLib = KnownFolders.MusicLibrary;
var files = await musicLib.GetFilesAsync();
foreach (var file in files)
{
StorageItemThumbnail currentThumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 50, ThumbnailOptions.UseCurrentScale);
var albumCover = new BitmapImage();
albumCover.SetSource(currentThumb);
var musicProperties = await file.Properties.GetMusicPropertiesAsync();
var musicname = musicProperties.Title;
var musicdur = musicProperties.Duration;
var artist = musicProperties.Artist;
if (artist == "")
{
artist = "Unknown";
}
var album = musicProperties.Album;
if (album == "")
{
album = "Unknown";
}
MusicList.Add(new MusicLib
{
FileName = musicname,
Artist = artist,
Album = album,
Duration = musicdur,
AlbumCover = albumCover,
MusicPath = file.Path
});
}
}
private async void SongClicked(object sender, ItemClickEventArgs e)
{
var file = await KnownFolders.MusicLibrary.GetFileAsync(e.ClickedItem.ToString());
if (file != null)
{
var stream = await file.OpenReadAsync();
mediaElement.SetSource(stream, file.ContentType);
mediaElement.Play();
}
}
private async void objMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
{
// If the end of the ListView is reached and the last song was played stop.
if ((AudioFilesLV.SelectedIndex + 1) == AudioFilesLV.Items.Count)
{
mediaElement.Stop();
}
else
{
// This line you should try to change. When the last song was not played
//-> select next one and play them.
AudioFilesLV.SelectedIndex = AudioFilesLV.SelectedIndex + 1;
var file = await KnownFolders.MusicLibrary.GetFileAsync(AudioFilesLV.SelectedItem.ToString());
if (file != null)
{
var stream = await file.OpenReadAsync();
mediaElement.SetSource(stream, file.ContentType);
mediaElement.Play();
}
}
}
So basically after you click on the song to play it should then automatically go to the next song and play it. I haven't got to that stage yet as it does not want to play the song I clicked.
Thanks
Try to cast e.ClickedItem
to a MusicLib
and then pass its MusicPath
to the GetFileAsync
method:
private async void SongClicked(object sender, ItemClickEventArgs e)
{
var clickedItem = e.ClickedItem as MusicLib;
if (clickedItem != null)
{
var file = await KnownFolders.MusicLibrary.GetFileAsync(clickedItem.MusicPath);
if (file != null)
{
var stream = await file.OpenReadAsync();
mediaElement.SetSource(stream, file.ContentType);
mediaElement.Play();
}
}
}
User contributions licensed under CC BY-SA 3.0