Exemplo n.º 1
0
        private void SendMessage(string constants)// SendMessage(constants,"")
        {
            var value = new ValueSet();

            value.Add(constants, "");
            BackgroundMediaPlayer.SendMessageToBackground(value);
        }
Exemplo n.º 2
0
 /// <summary>
 /// Отправляет сообщение фоновому процессу проигрывателя.
 /// </summary>
 /// <param name="message">Сообщение для отправки.</param>
 private void SendMessageToBackground(ValueSet message)
 {
     if (IsTaskRunning)
     {
         BackgroundMediaPlayer.SendMessageToBackground(message);
     }
 }
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to:
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                // immediately set not running
                backgroundTaskStarted.Reset();

                //save state
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Canceled.ToString());

                // unsubscribe event handlers
                BackgroundMediaPlayer.MessageReceivedFromForeground -= BackgroundMediaPlayer_MessageReceivedFromForeground;
                smtc.ButtonPressed   -= smtc_ButtonPressed;
                smtc.PropertyChanged -= smtc_PropertyChanged;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Exemplo n.º 4
0
 void SendMessage(string key, string value)
 {
     BackgroundMediaPlayer.SendMessageToForeground(new ValueSet
     {
         { key, value }
     });
 }
Exemplo n.º 5
0
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            try
            {
                ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_CURRENT_TRACK, Playlist.CurrentTrackName);
                ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_POSITION, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_STATE, SharedStrings.BACKGROUND_AUDIO_CANCELLED);
                ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_APP_STATE, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
                backgroundTaskRunning = false;

                if (transportControl != null)
                {
                    transportControl.ButtonPressed   -= transportControl_ButtonPressed;
                    transportControl.PropertyChanged -= transportControl_PropertyChanged;
                }
                Playlist.TrackChanged -= playList_TrackChanged;

                playlistManager.ClearPlaylist();
                playlistManager = null;
                BackgroundMediaPlayer.Shutdown();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("CoffeeBackgroundAudioTask.OnCanceled: " + ex.ToString());
            }
            if (deferral != null)
            {
                deferral.Complete();
                deferral = null;
            }
        }
Exemplo n.º 6
0
        async private void ResetBackgroundAudio()
        {
            BackgroundMediaPlayer.Shutdown();
            await Task.Delay(TimeSpan.FromSeconds(2));

            StartBackgroundAudioTask();
        }
Exemplo n.º 7
0
        private void StartBackgroundAudioTask()
        {
            AddMediaPlayerEventHandlers();
            bool         success        = false;
            IAsyncAction taskInitResult = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                success = taskInitialized.WaitOne(2000);
                if (success)
                {
                    ValueSet message = new ValueSet();
                    message.Add(SharedStrings.BACKGROUND_AUDIO_START_PLAYBACK, "0");
                    BackgroundMediaPlayer.SendMessageToBackground(message);
                    status.Log(LocalizableStrings.BACKGROUND_AUDIO_TASK_INVOKED);
                }
                else
                {
                    status.Log(SharedStrings.BACKGROUND_AUDIO_STARTUP_TIMEOUT);
                }
            });

            if (success)
            {
                taskInitResult.Completed = new AsyncActionCompletedHandler(taskInitResult_Completed);
            }
        }
Exemplo n.º 8
0
        private void ResetAfterLostBackground()
        {
            BackgroundMediaPlayer.Shutdown();
            _isMyBackgroundTaskRunning = false;
            backgroundAudioTaskStarted.Reset();
            audioPlayer.CanGoPrevious = false;
            audioPlayer.CanGoNext     = false;
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Unknow.ToString());
            audioPlayer.IsPlaying = true;

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        ///     Handles background task cancellation. Task cancellation happens due to :
        ///     1. Another Media app comes into foreground and starts playing music
        ///     2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        ///     In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                if (_queueManager != null)
                {
                    QueueManager.TrackChanged -= playList_TrackChanged;
                    _queueManager              = null;
                }

                _appSettingsHelper.Write(PlayerConstants.BackgroundTaskState,
                                         PlayerConstants.BackgroundTaskCancelled);

                _backgroundtaskrunning = false;
                //unsubscribe event handlers
                _systemmediatransportcontrol.ButtonPressed   -= systemmediatransportcontrol_ButtonPressed;
                _systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            if (_deferral != null)
            {
                _deferral.Complete(); // signals task completion.
                Debug.WriteLine("AudioPlayer Cancel complete...");
            }
        }
        private static void QueryForBackgroundTask()
        {
            ValueSet message = new ValueSet();

            message.Add(Constants.BackgroundTaskQuery, null);
            BackgroundMediaPlayer.SendMessageToBackground(message);
        }
Exemplo n.º 11
0
        /// <summary>
        ///     Handles background task cancellation. Task cancellation happens due to:
        ///     1. Another Media app comes into foreground and starts playing music
        ///     2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        ///     In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                // immediately set not running
                TaskStarted.Reset();

                // Dispose
                _playerWrapper.Dispose();
                _smtcWrapper.Dispose();
                _foregroundMessenger.Dispose();

                // shutdown media pipeline
                BackgroundMediaPlayer.Shutdown();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            _settingsUtility.Write(ApplicationSettingsConstants.BackgroundTaskState,
                                   BackgroundTaskState.Canceled);

            _deferral.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
        public static void StopPlayback()
        {
            ValueSet message = new ValueSet();

            message.Add(Constants.StopPlayback, null);
            BackgroundMediaPlayer.SendMessageToBackground(message);
        }
        public static void PauseCurrentSong()
        {
            ValueSet message = new ValueSet();

            message.Add(Constants.PauseTrack, null);
            BackgroundMediaPlayer.SendMessageToBackground(message);
        }
Exemplo n.º 14
0
        public void SendMessage(string constants, object value)
        {
            var message = new ValueSet();

            message.Add(constants, value);
            BackgroundMediaPlayer.SendMessageToBackground(message);
        }
Exemplo n.º 15
0
        private static void SendMessageToBackground(string name, object parameter)
        {
            var valueSet = new ValueSet();

            valueSet.Add(name, parameter);
            BackgroundMediaPlayer.SendMessageToBackground(valueSet);
        }
Exemplo n.º 16
0
        public async void PlaySong(QueueSong song)
        {
            if (song == null || song.Song == null)
            {
                CurtainPrompt.ShowError("Song seems to be empty...");
                return;
            }

            Insights.Track(
                "Play Song",
                new Dictionary <string, string>
            {
                { "Name", song.Song.Name },
                { "ArtistName", song.Song.ArtistName },
                { "ProviderId", song.Song.ProviderId }
            });

            if (_isShutdown)
            {
                await AddMediaPlayerEventHandlers();
            }

            _appSettings.Write("RadioId", null);
            _appSettings.Write("RadioMode", false);
            _appSettings.Write(PlayerConstants.CurrentTrack, song.Id);

            var message = new ValueSet {
                { PlayerConstants.StartPlayback, null }
            };

            BackgroundMediaPlayer.SendMessageToBackground(message);

            RaiseEvent(TrackChanged);
        }
Exemplo n.º 17
0
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            SaveText(DateTime.Now.Ticks, "Cancel", id, reason);

            BackgroundMediaPlayer.Shutdown();
            deferral.Complete();
        }
Exemplo n.º 18
0
        /// <summary>
        /// Called when IMediaPlayer [status changed].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void OnStatusChanged(object sender, EventArgs eventArgs)
        {
            if (this.mediaPlayer.Status == PlayerStatus.PLAYING)
            {
                //ThreadPool.RunOnUIThread(
                // async () =>
                // {
                if (BackgroundMediaPlayer.Current.CurrentState == MediaPlayerState.Paused)
                {
                    BackgroundMediaPlayer.Current.Play();
                }
                else
                {
                    //var file = this.trackMediaHelper.GetFileByMediaType(this.viewModel.CurrentTrack, TrackMediaType.AUDIO);

                    //this.mediaPlayer.Duration = file.Duration;
                    //this.viewModel.RaisePropertyChanged("Duration");

                    var fileUri = "";         //await this.trackMediaHelper.GetAuthenticatedUri(file);

                    BackgroundMediaPlayer.SendMessageToBackground(new ValueSet {
                        { "SetSource", fileUri.ToString() }
                    });
                }
                // });
            }
            else if (this.mediaPlayer.Status == PlayerStatus.PAUSED)
            {
                //ThreadPool.RunOnUIThread(
                //    async () =>
                //   {
                BackgroundMediaPlayer.Current.Pause();
                //   });
            }
        }
Exemplo n.º 19
0
    public void SendMessageToBackground(String x, String y)
    {
        ValueSet valueSet = new ValueSet();

        valueSet.Add(x, y);
        BackgroundMediaPlayer.SendMessageToBackground(valueSet);
    }
Exemplo n.º 20
0
        private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            SaveText(DateTime.Now.Ticks, "Complete", id, sender.Name);

            BackgroundMediaPlayer.Shutdown();
            deferral.Complete();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to :
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                //save state
                ApplicationSettingsHelper.SaveSettingsValue(Constants.CurrentTrack, Playlist.CurrentTrackName);
                ApplicationSettingsHelper.SaveSettingsValue(Constants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(Constants.BackgroundTaskState, Constants.BackgroundTaskCancelled);
                ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
                backgroundtaskrunning = false;
                //unsubscribe event handlers
                systemmediatransportcontrol.ButtonPressed   -= systemmediatransportcontrol_ButtonPressed;
                systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;
                Playlist.TrackChanged -= playList_TrackChanged;

                //clear objects task cancellation can happen uninterrupted
                playlistManager.ClearPlaylist();
                playlistManager = null;
                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
        /// <summary>
        /// Performs the work of a background task. The system calls this method when the associated
        /// background task has been triggered.
        /// </summary>
        /// <param name="taskInstance">
        /// An interface to an instance of the background task. The system creates this instance when the
        /// task has been triggered to run.
        /// </param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting");

            this.systemMediaTransportControl                   = SystemMediaTransportControls.GetForCurrentView();
            this.systemMediaTransportControl.IsEnabled         = true;
            this.systemMediaTransportControl.IsPauseEnabled    = true;
            this.systemMediaTransportControl.IsPlayEnabled     = true;
            this.systemMediaTransportControl.IsNextEnabled     = true;
            this.systemMediaTransportControl.IsPreviousEnabled = true;

            // Wire up system media control events
            this.systemMediaTransportControl.ButtonPressed   += this.OnSystemMediaTransportControlButtonPressed;
            this.systemMediaTransportControl.PropertyChanged += this.OnSystemMediaTransportControlPropertyChanged;

            // Wire up background task events
            taskInstance.Canceled       += this.OnTaskCanceled;
            taskInstance.Task.Completed += this.OnTaskcompleted;

            // Initialize message channel
            BackgroundMediaPlayer.MessageReceivedFromForeground += this.OnMessageReceivedFromForeground;

            // Notify foreground that we have started playing
            BackgroundMediaPlayer.SendMessageToForeground(new ValueSet()
            {
                { "BackgroundTaskStarted", "" }
            });
            this.backgroundTaskStarted.Set();
            this.backgroundTaskRunning = true;

            this.deferral = taskInstance.GetDeferral();
        }
Exemplo n.º 23
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;

            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                try
                {
                    if (BackgroundMediaPlayer.Current.PlaybackSession.PlaybackState == MediaPlaybackState.Paused | BackgroundMediaPlayer.Current.PlaybackSession.PlaybackState == MediaPlaybackState.None)
                    {
                        (Radio.Icon as BitmapIcon).UriSource = uriMute;
                    }
                    if (BackgroundMediaPlayer.Current.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
                    {
                        (Radio.Icon as BitmapIcon).UriSource = uriSound;
                    }
                } catch (Exception)
                {
                    (Radio.Icon as BitmapIcon).UriSource = uriMute;
                    BackgroundMediaPlayer.Shutdown();
                }
            });

            BackgroundMediaPlayer.Current.CurrentStateChanged += radioPlayer_CurrentStateChanged;
        }
Exemplo n.º 24
0
        private void ResetAfterLostBackground()
        {
            BackgroundMediaPlayer.Shutdown();
            _isMyBackgroundTaskRunning = false;
            backgroundAudioTaskStarted.Reset();
            //prevButton.IsEnabled = true;
            //nextButton.IsEnabled = true;
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Unknown.ToString());
            Pause.Icon = new SymbolIcon(Symbol.Pause);

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 25
0
        private void SendMessageToBackground(PlayQueueConstantFGMessageId messageId, object value)
        {
            var message = new ValueSet();

            message.Add(PlayQueueMessageHelper.FGMessageIdToMessageString(messageId), value);
            BackgroundMediaPlayer.SendMessageToBackground(message);
        }
Exemplo n.º 26
0
        /// <summary>
        /// The background task did exist, but it has disappeared. Put the foreground back into an initial state. Unfortunately,
        /// any attempts to unregister things on BackgroundMediaPlayer.Current will fail with the RPC error once the background task has been lost.
        /// </summary>
        private void ResetAfterLostBackground()
        {
            BackgroundMediaPlayer.Shutdown();
            _isMyBackgroundTaskRunning = false;
            backgroundAudioTaskStarted.Reset();
            PreviousButtonIsEnabled = true;
            NextButtonIsEnabled     = true;
            StopButtonVisibility    = Visibility.Collapsed;
            PlayButtonVisibility    = Visibility.Visible;
            PlayButtonIsEnabled     = true;
            RefreshBindings();

            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Unknown.ToString());

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Sends message to background informing app has resumed
        /// Subscribe to MediaPlayer events
        /// </summary>
        void ForegroundApp_Resuming(object sender, object e)
        {
            ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Constants.ForegroundAppActive);

            // Verify if the task was running before
            if (IsMyBackgroundTaskRunning)
            {
                //if yes, reconnect to media play handlers
                AddMediaPlayerEventHandlers();

                //send message to background task that app is resumed, so it can start sending notifications
                ValueSet messageDictionary = new ValueSet();
                messageDictionary.Add(Constants.AppResumed, DateTime.Now.ToString());
                BackgroundMediaPlayer.SendMessageToBackground(messageDictionary);

                if (BackgroundMediaPlayer.Current.CurrentState == MediaPlayerState.Playing)
                {
                    playButton.Content = "| |";     // Change to pause button
                }
                else
                {
                    playButton.Content = ">";     // Change to play button
                }
                txtCurrentTrack.Text = CurrentTrack;
            }
            else
            {
                playButton.Content   = ">";   // Change to play button
                txtCurrentTrack.Text = "";
            }
        }
        /// <summary>
        /// The background task did exist, but it has disappeared. Put the foreground back into an initial state. Unfortunately,
        /// any attempts to unregister things on BackgroundMediaPlayer.Current will fail with the RPC error once the background task has been lost.
        /// </summary>
        private void ResetAfterLostBackground()
        {
            backgroundAudioTaskStarted.Reset();
            BackgroundMediaPlayer.Shutdown();

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground -= BackgroundPlayerMessageReceivedFromBackground;
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundPlayerMessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    telemetry.TrackException(ex, new Dictionary <string, string> {
                        { "Scenario", "ResetPlayerServerUnavailable" }
                    });
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 29
0
        private void HandleTaskInstanceCanceled(IBackgroundTaskInstance taskInstance, BackgroundTaskCancellationReason reason)
        {
            PlayQueueManager.Current.Disconnect();

            TileUpdateManager.CreateTileUpdaterForApplication("App").Clear();

            Logger.Current.Log(new CallerInfo(), LogLevel.Info, "AudioPlayer Background Task Completed id:{0} reason:{1}", taskInstance.Task.TaskId, reason.ToString());

            ApplicationSettings.PutSettingsValue(ApplicationSettings.IS_BACKGROUND_PROCESS_ACTIVE, false);

            if (ApplicationSettings.GetSettingsValue <bool>(ApplicationSettings.IS_FOREGROUND_PROCESS_ACTIVE, false))
            {
                PlayQueueManager.Current.SendMessageToForeground(PlayQueueConstantBGMessageId.BackgroundEnded);
            }

            backgroundTaskState = BackgroundTaskState.Stopped;

            PlayQueueManager.Current.TrackChanged -= HandlePlayQueueTrackChanged;

            BackgroundMediaPlayer.Current.CurrentStateChanged -= HandleBackgroundMediaPlayerCurrentStateChanged;
            taskInstance.Task.Completed -= HandleTaskInstanceTaskCompleted;
            taskInstance.Canceled       -= HandleTaskInstanceCanceled;

            BackgroundMediaPlayer.Shutdown();

            Logger.Current.Flush();

            backgroundTaskDefferal.Complete();
        }
Exemplo n.º 30
0
        private async void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            ToggleSwitch toggleSwitch = sender as ToggleSwitch;

            if (toggleSwitch != null)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    if (toggleSwitch.IsOn)
                    {
                        if (BackgroundMediaPlayer.Current.CurrentState != MediaPlayerState.Playing)
                        {
                            var message = new ValueSet
                            {
                                {
                                    "Play",
                                    urlRadio
                                }
                            };
                            BackgroundMediaPlayer.SendMessageToBackground(message);
                        }
                    }
                    else
                    {
                        BackgroundMediaPlayer.Current.Pause();
                    }
                });
            }
        }
        public void OnActivated(BackgroundMediaPlayer mediaPlayer)
        {
            _codecManager = new CodecManager();
            _codecManager.RegisterDefaultCodecs();

            this.mediaPlayer = mediaPlayer;
            smtc = mediaPlayer.SystemMediaTransportControls;
            ConfigureSystemMediaTransportControls();
            mediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
            mediaPlayer.MediaEnded += MediaPlayer_MediaEnded;
            mediaPlayer.CurrentStateChanged += MediaPlayer_CurrentStateChanged;
            Switch();
        }