我正在开发我的Project(一个soundcloud客户端),该应用程序可以很好地播放曲目,但不会在应用程序最小化时播放。我使用MediaElement-Object从url播放mp3。当应用程序在后台时,如何强制音乐继续播放音乐。或者最简单的方法/最好的解释教程来实现这一点。我搜索了很多很好的答案,但我发现,这些对我来说太好了:D什么意思,我不明白。
答案 0 :(得分:5)
要在后台播放音频,您必须在Package.appxmanifest
中为后台任务执行声明,启用音频并添加TestUWP.MainPage
页面等入口点。
另外,为了让用户能够轻松管理音频,您可以使用SystemMediaTransportControls
以下是播放和暂停的基本设置。
XAML
<MediaElement x:Name="mediaElement" Height="100" Width="100" AreTransportControlsEnabled="True"/>
C#
public MainPage()
{
this.InitializeComponent();
systemControls = SystemMediaTransportControls.GetForCurrentView();
// Register to handle the following system transpot control buttons.
systemControls.ButtonPressed += SystemControls_ButtonPressed;
mediaElement.CurrentStateChanged += MediaElement_CurrentStateChanged;
systemControls.IsPlayEnabled = true;
systemControls.IsPauseEnabled = true;
}
private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
switch (mediaElement.CurrentState)
{
case MediaElementState.Playing:
systemControls.PlaybackStatus = MediaPlaybackStatus.Playing;
break;
case MediaElementState.Paused:
systemControls.PlaybackStatus = MediaPlaybackStatus.Paused;
break;
case MediaElementState.Stopped:
systemControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
break;
case MediaElementState.Closed:
systemControls.PlaybackStatus = MediaPlaybackStatus.Closed;
break;
default:
break;
}
}
void SystemControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
PlayMedia();
break;
case SystemMediaTransportControlsButton.Pause:
PauseMedia();
break;
case SystemMediaTransportControlsButton.Stop:
StopMedia();
break;
default:
break;
}
}
private async void StopMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
mediaElement.Stop();
});
}
async void PlayMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if (mediaElement.CurrentState == MediaElementState.Playing)
mediaElement.Pause();
else
mediaElement.Play();
});
}
async void PauseMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
mediaElement.Pause();
});
}
输出
如果您想启用更多控件,可以使用ex的可用属性。
systemControls.IsNextEnabled = true;
,您必须在按钮开关中添加case
。
case SystemMediaTransportControlsButton.Next:
//handle next song
break;
答案 1 :(得分:2)
您需要使用BackgroundAudio任务才能在Windows Mobile上运行。本文将引导您完成Microsoft提供的github示例。 https://blogs.windows.com/buildingapps/2016/01/13/the-basics-of-background-audio/