/// <summary> /// 执行暂停命令 /// </summary> public void Pause() { if (IsBackgroundRunning) { BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.TRACK_INDEX, CurrentPlayingIndex); BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.POSITION, CurrentPlayer.Position.ToString()); CurrentPlayer.Pause(); } }
/// <summary> /// 后台任务的入口方法 /// </summary> /// <param name="taskInstance">表示当前任务的实例</param> public void Run(IBackgroundTaskInstance taskInstance) { //初始化后台消息处理的线程锁 o = new object(); //初始化系统音频控制器 smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls; smtc.ButtonPressed += Smtc_ButtonPressed; smtc.PropertyChanged += Smtc_PropertyChanged; smtc.IsEnabled = true; smtc.IsNextEnabled = true; smtc.IsPreviousEnabled = true; smtc.IsPlayEnabled = true; smtc.IsPauseEnabled = true; //获取前台APP状态 var appState = BackgroundAudioSettingsHelper.GetValue(BackgroundAudioSettingsConstants.APP_STATE); if (appState == null) { foregroundAppState = AppState.Unknown; } else { foregroundAppState = EnumHelper.Parse <AppState>(appState.ToString()); } //注册后台播放器的状态改变事件 BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged; //注册后台播放器发生错误时的事件 BackgroundMediaPlayer.Current.MediaFailed += Current_MediaFailed; BackgroundMediaPlayer.Current.MediaEnded += Current_MediaEnded; //注册后台播放器接收前台消息事件 BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground; //如果前台APP未处于挂起状态,发送后台音频启动消息给前台 if (foregroundAppState != AppState.Suspended) { MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage()); } //保存后台音频任务的启动状态 BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.BACKGROUND_TASK_STATE, BackgroundTaskState.Running.ToString()); deferral = taskInstance.GetDeferral(); backgroundTaskStarted.Set(); //注册后台任务结束事件 taskInstance.Task.Completed += Task_Completed; //注册后台任务取消事件 taskInstance.Canceled += TaskInstance_Canceled; }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { //#if DEBUG // if (System.Diagnostics.Debugger.IsAttached) // { // this.DebugSettings.EnableFrameRateCounter = true; // } //#endif //Frame rootFrame = Window.Current.Content as Frame; MainFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (MainFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page MainFrame = new Frame(); MainFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = MainFrame; } if (e.PrelaunchActivated == false) { if (MainFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter MainFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.APP_STATE, AppState.Active.ToString()); try { UDPServer.StartService("14288"); RemoteControlService.StartService(); } catch (Exception ex) { throw new Exception("启动UDP服务失败", ex); } } DispatcherHelper.Initialize(); }
/// <summary> /// 后台任务取消的event handler /// </summary> /// <param name="sender"></param> /// <param name="reason">取消原因</param> private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { Debug.WriteLine("BackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested..."); try { backgroundTaskStarted.Reset(); //保存前后台任务状态和歌曲播放信息 BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.TRACK_INDEX, playbackList.CurrentItemIndex); BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.POSITION, BackgroundMediaPlayer.Current.Position.ToString()); BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.BACKGROUND_TASK_STATE, BackgroundTaskState.Canceled.ToString()); BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.APP_STATE, Enum.GetName(typeof(AppState), foregroundAppState)); //清空播放列表 if (playbackList != null) { //playbackList.CurrentItemChanged -= PlaybackList_CurrentItemChanged; playbackList = null; } //取消注册时间 BackgroundMediaPlayer.MessageReceivedFromForeground -= BackgroundMediaPlayer_MessageReceivedFromForeground; smtc.ButtonPressed -= Smtc_ButtonPressed; smtc.PropertyChanged -= Smtc_PropertyChanged; //发送后台任务停止消息给前台 MessageService.SendMessageToForeground(new BackgroundAudioTaskStopedMessage()); //关闭后台播放器 BackgroundMediaPlayer.Shutdown(); } catch (Exception ex) { Debug.WriteLine(ex.ToString() + " " + ex.Message); } finally { deferral.Complete(); Debug.WriteLine("BackgroundAudioTask Cancel Completed"); } }
/// <summary> /// 后台任务异常关闭时,重新启动关闭的后台任务 /// </summary> private void ResetAfterLostBackground() { BackgroundMediaPlayer.Shutdown(); _isBackgroundRunning = false; BackgroundAudioTaskStarted.Reset(); BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.BACKGROUND_TASK_STATE, BackgroundTaskState.Unknown.ToString()); try { BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground; } catch (Exception ex) { if (ex.HResult == RPC_S_SERVER_UNAVAILABLE) { throw new Exception("Fail to get a media instance", ex); } throw ex; } }
/// <summary> /// 接收到前台消息的event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e) { lock (o) { Debug.WriteLine("接收消息" + e.Data); AppSuspendingMessage appSuspendingMessage; if (MessageService.TryParseMessage(e.Data, out appSuspendingMessage)) { Debug.WriteLine("App Suspending"); foregroundAppState = AppState.Suspended; BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.TRACK_INDEX, playbackList == null ? uint.MinValue : playbackList.CurrentItemIndex); return; } AppResumedMessage appResumedMessage; if (MessageService.TryParseMessage(e.Data, out appResumedMessage)) { Debug.WriteLine("App Resumed"); foregroundAppState = AppState.Active; return; } StartPlaybackMessage startPlaybackMessage; if (MessageService.TryParseMessage(e.Data, out startPlaybackMessage)) { Debug.WriteLine("Starting Playback"); StartPlayback(); return; } SkipNextMessage skipNextMessage; if (MessageService.TryParseMessage(e.Data, out skipNextMessage)) { Debug.WriteLine("Skip to Next"); SkipToNext(); return; } SkipPreviousMessage skipPreviousMessage; if (MessageService.TryParseMessage(e.Data, out skipPreviousMessage)) { Debug.WriteLine("Skip to Previous"); SkipToPrevious(); return; } UpdatePlaybackListMessage updatePlaybackListMessage; if (MessageService.TryParseMessage(e.Data, out updatePlaybackListMessage)) { Debug.WriteLine("Update Playback list"); //CreatePlaybackList(updatePlaybackListMessage.Songs); CreatePlaylist(updatePlaybackListMessage.Songs); isFirstTimeToStart = !updatePlaybackListMessage.IsResumed; return; } TrackChangeMessage trackChangeMessage; if (MessageService.TryParseMessage(e.Data, out trackChangeMessage)) { Debug.WriteLine("---------------Track Change" + trackChangeMessage.TrackIndex + "当前track:" + currentIndex); int index = trackChangeMessage.TrackIndex; //smtc.PlaybackStatus = MediaPlaybackStatus.Changing; try { //currentIndex = (int)index; //var item = playbackList.MoveTo(index); PlayIndex(index); } catch { } //int index = playbackList.Items.ToList().FindIndex(p => (string)p.Source.CustomProperties["filename"] == trackChangeMessage.TrackFile); //Debug.WriteLine("切换歌曲: " + index + "---" + trackChangeMessage.TrackFile); //smtc.PlaybackStatus = MediaPlaybackStatus.Changing; //playbackList.MoveTo((uint)index); return; } Debug.WriteLine("处理消息结束"); } }