【发布时间】:2015-07-01 03:26:48
【问题描述】:
我通过 msdn 站点、stackoverflow 等进行了很多搜索。但我无法在后台播放歌曲。它在更改框架时停止,或者从应用程序退出返回开始,当它在锁屏或其他地方时它也会随机启动..你能解释一下这段代码的正确性吗?抱歉代码不好,但我几天前就开始了。
这或多或少是我在微软网站上找到的。也没有不显示任何控制的系统
public sealed partial class listView : Page
{
SystemMediaTransportControls Player = SystemMediaTransportControls.GetForCurrentView();
SystemMediaTransportControls systemControls;
MediaElement musicPlayer = new MediaElement();
public listView()
{
this.InitializeComponent();
makeSongList();
// Per usare il tasto back
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
// Hook up app to system transport controls.
systemControls = SystemMediaTransportControls.GetForCurrentView();
systemControls.ButtonPressed += SystemControls_ButtonPressed;
// Register to handle the following system transpot control buttons.
systemControls.IsEnabled = true;
systemControls.IsPlayEnabled = true;
systemControls.IsPauseEnabled = true;
systemControls.IsNextEnabled = true;
systemControls.IsPreviousEnabled = true;
musicPlayer.AudioCategory = AudioCategory.BackgroundCapableMedia;
}
void MusicPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
{
// gestisce l'evento CurrentStateChanged di MediaElement e
// aggiorna la proprietà PlaybackStatus di SystemMediaTransportControls.
switch (musicPlayer.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;
}
}
async private void UpdateSongInfo()
{
// Get the updater.
SystemMediaTransportControlsDisplayUpdater updater = systemControls.DisplayUpdater;
// Get the music file and pass it to CopyFromFileAsync to extract the metadata
// and thumbnail. StorageFile is defined in Windows.Storage
StorageFile musicFile =
await StorageFile.GetFileFromApplicationUriAsync(new Uri(currentPath));
await updater.CopyFromFileAsync(MediaPlaybackType.Music, musicFile);
// Update the system media transport controls
updater.Update();
}
void MusicPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
UpdateSongInfo();
}
void SystemControls_ButtonPressed(SystemMediaTransportControls sender,
SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
PlayMedia();
break;
case SystemMediaTransportControlsButton.Pause:
PauseMedia();
break;
default:
break;
}
}
async void PlayMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
musicPlayer.Play();
});
}
async void PauseMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
musicPlayer.Pause();
});
}
【问题讨论】:
标签: c# wpf xaml windows-phone-8.1