The Background Audio sample uses MediaSource.CreateFromUri method to create media source. While using this method, the parameter can only be set to the Uniform Resource Identifier (URI) of a file that is included with the app or the URI of a file on the network. To set the source to a file retrieved from the local system by using a FileOpenPicker object, we can use MediaSource.CreateFromStorageFile method. And whenever our app accesses a file or folder through a picker, we can add it to app's FutureAccessList or MostRecentlyUsedList to keep track of it.
For example, after we get the StorageFile
from FileOpenPicker
, we can add it to FutureAccessList
and store the token that the app can use later to retrieve the storage item in app's local settings like:
if (file != null)
{
var token = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
ApplicationData.Current.LocalSettings.Values["song1"] = token;
}
For more info about FutureAccessList
, please see Track recently used files and folders.
Then in BackgroundAudioTask
, I changed CreatePlaybackList
method to replace the original like:
private async void CreatePlaybackList(IEnumerable<SongModel> songs)
{
// Make a new list and enable looping
playbackList = new MediaPlaybackList();
playbackList.AutoRepeatEnabled = true;
// Add playback items to the list
foreach (var song in songs)
{
MediaSource source;
//Replace Ring 1 to the song we select
if (song.Title.Equals("Ring 1"))
{
var file = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(ApplicationData.Current.LocalSettings.Values["song1"].ToString());
source = MediaSource.CreateFromStorageFile(file);
}
else
{
source = MediaSource.CreateFromUri(song.MediaUri);
}
source.CustomProperties[TrackIdKey] = song.MediaUri;
source.CustomProperties[TitleKey] = song.Title;
source.CustomProperties[AlbumArtKey] = song.AlbumArtUri;
playbackList.Items.Add(new MediaPlaybackItem(source));
}
// Don't auto start
BackgroundMediaPlayer.Current.AutoPlay = false;
// Assign the list to the player
BackgroundMediaPlayer.Current.Source = playbackList;
// Add handler for future playlist item changes
playbackList.CurrentItemChanged += PlaybackList_CurrentItemChanged;
}
This is just a simple sample, you may need to change the SongModel
and some other code to implement your own player. For more info about Background Audio, you can also refer to The Basics of Background Audio. Besides, with Windows 10, version 1607, significant improvements were made to the media playback APIs, including a simplified single-process design for background audio. You can see Play media in the background to check the new feature.