Access music files UWP -KnownFolders.MusicLibrary.

2019-09-14 18:13发布

问题:

Hey i have the following :

 var fileList = await KnownFolders.MusicLibrary.GetItemsAsync();

It doesn't return any files and i have files in the Music folder. I also have :

<Capabilities>
<Capability Name="internetClient" />
<Capability Name="removableStorage" />
<Capability Name="documentsLibrary" />
<Capability Name="MusicLibrary" />
<Capability Name="HomeGroup" />
<Capability Name="RemovableDevices" />

I dont know why it doesnt return any files/ exception ? Any suggestions ? I also tried FolderPicker to get all files in a folder , but same result.

回答1:

Form the code you've posted, it seems you are using wrong capabilities.

The musicLibrary capability must include the uap namespace when you declare it in your app's package manifest as shown below.

<Capabilities><uap:Capability Name="musicLibrary"/></Capabilities>

For more info, please see App capability declarations.

So you can chane your Package.appxmanifest like the following:

<Capabilities>
  <Capability Name="internetClient" />
  <uap:Capability Name="removableStorage" />
  <uap:Capability Name="musicLibrary" />
  <uap:Capability Name="documentsLibrary" />
</Capabilities>

And then you should be able to get the files and subfolders in the music library.

var fileList = await KnownFolders.MusicLibrary.GetItemsAsync();
if (fileList.Count > 0)
{
    foreach (var item in fileList)
    {
        Debug.WriteLine(item.Name);
    }
}

The Music Library typically has the following path.

%USERPROFILE%\Music

You can check if you have files under this path. And also you can check the path with the following code.

var musicLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Music);
Debug.WriteLine(musicLibrary.SaveFolder.Path);

This will output the path of the known folder, which is the folder in a library where new files are saved by default. For more info, please see this answer.