UI 和 BackgroundMediaPlayer 之间的通信可以通过by sending messages:
一个简单的通信机制会在前台和后台进程中引发事件。 SendMessageToForeground 和 SendMessageToBackground 方法各自调用相应任务中的事件。数据可以作为参数传递给接收任务中的事件处理程序。
您使用SendMessageToBackground 传递a simple object by using ValueSet。将其发送到您的 BMP 实例 后,MessageReceivedFromForeground event 会被引发,您可以从 MediaPlayerDataReceivedEventArgs 读取您传递的 object。
在您的情况下,例如,您可以将带有文件路径的字符串传递给您的播放器:
// the UI code - send from Foreground to Background
ValueSet message = new ValueSet();
message.Add("SetTrack", yourStorageFile.Path); // send path (string)
BackgroundMediaPlayer.SendMessageToBackground(message);
那么正如我所说 - 适当的事件是(应该)由 Player 实例引发:
private async void BMP_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
{
foreach (string key in e.Data.Keys)
{
switch (key)
{
case "SetTrack":
string passedPath = (string)e.Data.Values.FirstOrDefault();
//here code you want to perform - change track/stop other
// that depends on your needs
break;
// rest of the code
我强烈推荐阅读the mentioned overview at MSDN,调试你的程序,看看它是如何工作的。
另一方面,如果你只想从文件中设置轨道,你可以尝试这样(你不能在 UI 中设置 FileSource - 这是真的,但你可以使用 SetUriSource):
// for example playing the first file from MusicLibrary (I assume that Capabilities are set properly)
StorageFile file = (await KnownFolders.MusicLibrary.GetFilesAsync()).FirstOrDefault();
BackgroundMediaPlayer.Current.SetUriSource(new Uri(file.Path, UriKind.RelativeOrAbsolute));