0

Microsoft W10 通用应用背景音频示例可以播放存储在 ///Assets 中的 .wma 文件列表,如下所示:

var song2 = new SongModel();
song2.Title = "Ring 2";
song2.MediaUri = new Uri("ms-appx:///Assets/Media/Ring02.wma");
song2.AlbumArtUri = new Uri("ms-appx:///Assets/Media/Ring02.jpg");
playlistView.Songs.Add(song2);

但我无法让程序播放存储在磁盘上的 .wma 文件。我尝试使用 FileOpenPicker 选择一个文件,将其分配给 StorageFile 文件,然后:

if (file != null)
{
Uri uri = new Uri(file.Path);
song2.MediaUri = uri;
}

或者通过(临时)将它放在图片库(我检查了功能)中,我认为我可以像这样访问,但不是这种情况,或者它不起作用(很可能两者兼而有之):

string name = "ms-appdata:///local/images/SomeSong.wma";
Uri uri = new Uri(name, UriKind.Absolute);
song1.MediaUri = uri;

只有原始的 ///Assets WMA 是可听见的。

我应该改变什么?以及如何将 KnownFolders 目录转换为 Uri?

4

1 回答 1

0

背景音频示例使用MediaSource.CreateFromUri 方法创建媒体源。使用此方法时,该参数只能设置为应用程序包含的文件的统一资源标识符 (URI) 或网络上文件的 URI。要使用FileOpenPicker对象将源设置为从本地系统检索的文件,我们可以使用MediaSource.CreateFromStorageFile方法。并且每当我们的应用程序通过选择器访问文件或文件夹时,我们可以将其添加到应用程序的FutureAccessListMostRecentlyUsedList以跟踪它。

例如,在我们获得StorageFilefrom之后FileOpenPicker,我们可以将它添加到FutureAccessList并存储令牌,以便应用程序稍后可以使用它来检索应用程序本地设置中的存储项,例如:

if (file != null)
{
    var token = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);

    ApplicationData.Current.LocalSettings.Values["song1"] = token;
}

有关详细信息FutureAccessList,请参阅跟踪最近使用的文件和文件夹

然后在BackgroundAudioTask,我改变了CreatePlaybackList方法来替换原来的,比如:

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;
}

这只是一个简单的示例,您可能需要更改SongModel和其他一些代码来实现您自己的播放器。有关背景音频的更多信息,您还可以参考背景音频的基础知识。此外,在 Windows 10 版本 1607 中,对媒体播放 API 进行了重大改进,包括简化了背景音频的单进程设计。您可以在后台看到播放媒体以检查新功能。

于 2016-08-04T10:03:56.507 回答