我最近决定在我的应用中为播客添加背景音频播放支持。我已经完成了大部分工作但是,BackgroundMediaPlayer的SystemTransportControls中的暂停按钮似乎没有做任何事情。
这是我的后台音频任务类文件:
public sealed class AudioPlayer : IBackgroundTask
{
private BackgroundTaskDeferral _deferral;
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
var control = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
control.IsEnabled = true;
control.IsPauseEnabled = true;
control.IsPlayEnabled = true;
control.IsNextEnabled = false;
control.IsPreviousEnabled = false;
taskInstance.Canceled += TaskInstance_Canceled;
BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
}
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
BackgroundMediaPlayer.Shutdown();
_deferral.Complete();
}
void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
{
object obj;
e.Data.TryGetValue("MessageBody", out obj);
string url = (string)obj;
url = url.Replace("\"", "");
var source = MediaSource.CreateFromUri(new Uri(url, UriKind.Absolute));
var list = new MediaPlaybackList();
list.Items.Add(new MediaPlaybackItem(source));
BackgroundMediaPlayer.Current.Source = list;
BackgroundMediaPlayer.Current.Play();
}
}
重要的是要注意音频确实在后台开始播放,但我没有能力暂停音频。
谢谢, P上。
答案 0 :(得分:1)
要对SystemMediaTransportControls(SMTC)做出反应并处理每个通用音量控制(UVC)按钮:播放,暂停,下一个和上一个,我们需要处理Run
方法中的SystemMediaTransportControls.ButtonPressed event,如下所示:< / p>
public void Run(IBackgroundTaskInstance taskInstance)
{
var control = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
control.ButtonPressed += control_ButtonPressed;
...
}
在control_ButtonPressed
方法中,处理不同的按钮,如:
private void control_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
//Todo with play
break;
case SystemMediaTransportControlsButton.Pause:
//Todo with pause
break;
case SystemMediaTransportControlsButton.Next:
//Todo with skip to next;
break;
case SystemMediaTransportControlsButton.Previous:
//Todo with skip to previous;
break;
}
}
有关完整示例,请参阅GitHub上的官方Background audio sample,尤其是MyBackgroundAudioTask class。还有一个非常好的帖子将指导您设置背景音频,对设备媒体控件做出反应,与后台媒体播放器通信以及管理播放列表。阅读更多The Basics of Background Audio。