Search code examples
c#uwpurimediaplayback

UWP: MediaPlaybackItem get ViewModel


My MediaPlaybackList.ShuffledItems has 10 items in it. But when I was trying to convert the items back to a list of ViewModel (in my case it is Music) using the uri, I got null.

Why is that? Is it because I load the file from my local drive?

This is how I get the uri:

    public static async Task<List<Music>> GetRealPlayList()
    {
        if (PlayList.ShuffleEnabled)
        {
            if (ShuffledPlayList.Count == 0)
            {
                foreach (var music in PlayList.ShuffledItems)
                {
                    ShuffledPlayList.Add(await Music.GetMusic(music.Source.Uri.AbsolutePath));
                }
            }
            return ShuffledPlayList;
        }
        else
            return CurrentPlayList;
    }

This is how I set the items:

    public static async Task SetPlayList(IEnumerable<Music> playlist)
    {
        if (Helper.SamePlayList(playlist, CurrentPlayList)) return;
        PlayList.Items.Clear();
        CurrentPlayList.Clear();
        foreach (var music in playlist)
        {
            var item = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(await Helper.CurrentFolder.GetFileAsync(music.GetShortPath())));
            PlayList.Items.Add(item);
            CurrentPlayList.Add(music);
        }
    }

What ways else can I convert the MediaPlackBackItem back to the ViewModel? The GetDisplayProperties().MusicProperties doesn't have the some properties that I want and the properties in it are also empty.


Solution

  • When you create MediaSource,you can set CustomProperties to save the file path in it.And when you loop through the PlayList.ShuffledItems,get file path from the CustomProperties.

    Set the items:

    MediaSource source = MediaSource.CreateFromStorageFile(await Helper.CurrentFolder.GetFileAsync(music.GetShortPath()));
    source.CustomProperties.Add("Path", file.Path);
    var item = new MediaPlaybackItem(source);
    

    Get Music class:

    foreach (var music in PlayList.ShuffledItems)
    {​
        MediaSource source = music.Source;​
        String path = sour.CustomProperties["Path"].ToString();​
        ShuffledPlayList.Add(await Music.GetMusic(path));​
    }