public void Run(IBackgroundTaskInstance taskInstance)
        {
            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed += Smtc_ButtonPressed;
            smtc.PropertyChanged += Smtc_PropertyChanged;
            smtc.IsEnabled = true;
            smtc.IsPauseEnabled = true;
            smtc.IsPlayEnabled = true;
            smtc.IsNextEnabled = true;
            smtc.IsPreviousEnabled = true;
            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);
            if (value == null)
                foregroundAppState = AppState.Unknown;
            else
                foregroundAppState = EnumHelper.Parse<AppState>(value.ToString());
            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            if (foregroundAppState != AppState.Suspended)
                MessageService.SendMessageToForeground(new BackgroundTaskStateChangedMessage(BackgroundTaskState.Running));

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

            deferral = taskInstance.GetDeferral(); // This must be retrieved prior to subscribing to events below which use it
            ReadytoConfirmFiles();

            // Mark the background task as started to unblock SMTC Play operation (see related WaitOne on this signal)

            taskInstance.Task.Completed += TaskCompleted;
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
        }
Exemplo n.º 2
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");

            mdcontrol = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            mdcontrol.IsEnabled = true;
            // 允许使用播放/暂停按钮
            mdcontrol.IsPlayEnabled = true;
            mdcontrol.IsPauseEnabled = true;
            // 处理ButtonPressed事件
            mdcontrol.ButtonPressed += mdcontrol_ButtonPressed;
            // 获取MediaPlayer实例
            currentPlayer = BackgroundMediaPlayer.Current;
            // 处理事件,接收来自前台应用程序的消息
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            // 关闭自动开始播放
            currentPlayer.AutoPlay = false;
            // 设置播放源
            Uri audioUri = new Uri("ms-appx:///Assets/1.mp3");
            currentPlayer.SetUriSource(audioUri);
            deferral = taskInstance.GetDeferral();
            // 当后台任务被取消时引发事件
            taskInstance.Canceled += task_Canceled;
            isRunning = true;
        }
        /// <summary>
        /// The Run method is the entry point of a background task. 
        /// </summary>
        /// <param name="taskInstance"></param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");
            // Initialize SMTC object to talk with UVC.
            //Note that, this is intended to run after app is paused and
            //hence all the logic must be written to run in background process
            systemmediatransportcontrol = SystemMediaTransportControls.GetForCurrentView();
            systemmediatransportcontrol.ButtonPressed += systemmediatransportcontrol_ButtonPressed;
            systemmediatransportcontrol.PropertyChanged += systemmediatransportcontrol_PropertyChanged;
            systemmediatransportcontrol.IsEnabled = true;
            systemmediatransportcontrol.IsPauseEnabled = true;
            systemmediatransportcontrol.IsPlayEnabled = true;
            systemmediatransportcontrol.IsNextEnabled = true;
            systemmediatransportcontrol.IsPreviousEnabled = true;

            // Associate a cancellation and completed handlers with the background task.
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
            taskInstance.Task.Completed += Taskcompleted;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(Constants.AppState);
            if (value == null)
                foregroundAppState = ForegroundAppStatus.Unknown;
            else
                foregroundAppState = (ForegroundAppStatus)Enum.Parse(typeof(ForegroundAppStatus), value.ToString());

            //Add handlers for MediaPlayer
            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;

            deferral = taskInstance.GetDeferral();
        }
        /// <inheritdoc /> 
        protected override bool OnActivate()
        {
            if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                SystemControls = SystemMediaTransportControls.GetForCurrentView();
                SystemControls.ButtonPressed += SystemControls_ButtonPressed;
                RefreshFastForwardState();
                RefreshRewindState();
                RefreshStopState();
                RefreshPlayState();
                RefreshPauseState();
                RefreshNextState();
                RefreshPreviousState();
                RefreshPlaybackStatus();

                if (PlaylistPlugin != null)
                {
                    PlaylistPlugin.Playlist.CollectionChanged += Playlist_CollectionChanged;
                    PlaylistPlugin.CurrentPlaylistItemChanged += PlaylistPlugin_CurrentPlaylistItemChanged;
                }
                WireEvents(MediaPlayer.InteractiveViewModel);
                MediaPlayer.InteractiveViewModelChanged += MediaPlayer_InteractiveViewModelChanged;
                return true;
            }
            else return false;
        }
        private async void StartMediaElement()
        {
            // To use AudioCategory.BackgroundCapableMedia:
            // * OnWindows 8 set MediaControl.PlayPressed, MediaControl.PausePressed,
            //   MediaControl.PlayPauseTogglePressed and MediaControl.StopPressed.
            // * On Windows 8.1 set SystemMediaTransportControls.ButtonPressed.
            systemControls = SystemMediaTransportControls.GetForCurrentView();
            systemControls.ButtonPressed += OnButtonPressed;
            systemControls.IsPlayEnabled = true;
            systemControls.IsPauseEnabled = true;
            systemControls.PlaybackStatus = MediaPlaybackStatus.Playing;

            mediaPlayer = new MediaElement();
            mediaPlayer.AudioCategory = AudioCategory.BackgroundCapableMedia;
            mediaPlayer.AutoPlay = true;
            mediaPlayer.CurrentStateChanged += OnCurrentStateChanged;
            this.Content = mediaPlayer;

            HttpClient client = new HttpClient();

            // Add custom headers or credentials.
            client.DefaultRequestHeaders.Add("Foo", "Bar");

            //Uri uri = new Uri("http://localhost/song.mp3?slow=1000&?bufferlength=100000&lastModified=true");
            Uri uri = new Uri("http://video.ch9.ms/ch9/70cc/83e17e76-8be8-441b-b469-87cf0e6a70cc/ASPNETwithScottHunter_high.mp4");

            HttpRandomAccessStream stream = await HttpRandomAccessStream.CreateAsync(client, uri);

            // If you need to use HttpClient, use MediaElement.SetSource() instead of MediaElement.Source.
            mediaPlayer.SetSource(stream, stream.ContentType);
        }
Exemplo n.º 6
0
        public MediaPlayer()
        {
            //Initialize Page
            this.InitializeComponent();

            //NavigationHelper
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
            this.NavigationCacheMode = NavigationCacheMode.Required;

            //Load Settings
            MPS_Start_Settings();

            //Register to handle the following system transpot control buttons.
            systemControls = SystemMediaTransportControls.GetForCurrentView();
            systemControls.ButtonPressed += SystemMediaControls_ButtonPressed;
            systemControls.IsPlayEnabled = true;
            systemControls.IsPauseEnabled = true;
            systemControls.IsStopEnabled = true;
            systemControls.IsNextEnabled = true;
            systemControls.IsPreviousEnabled = true;
            systemControls.IsEnabled = true;

            DC.Trace("(MediaPlayer Loaded)");
            SetupTimer();
        }
        /// <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.º 8
0
        /// <summary>
        /// Hệ thống gọi đến hàm này khi association backgroundtask được bật
        /// </summary>
        /// <param name="taskInstance"> hệ thống tự tạo và truyền vào đây</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //System.Diagnostics.Debug.WriteLine("background run");
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(BackgroundTaskCanceled);
            taskInstance.Task.Completed += new BackgroundTaskCompletedEventHandler(BackgroundTaskCompleted);
            _backgroundstarted.Set();//
            _deferral = taskInstance.GetDeferral();

            //Playlist = new BackgroundPlaylist();
            _smtc = initSMTC();


            this._foregroundState = this.initForegroundState();

            BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayer_CurrentStateChanged;
            //Playlist = await BackgroundPlaylist.LoadBackgroundPlaylist("playlist.xml");
            Playlist = new BackgroundPlaylist();
            Playlist.ListPathsource = await BackgroundPlaylist.LoadCurrentPlaylist(Constant.CurrentPlaylist);
            
            if (_foregroundState != eForegroundState.Suspended)
            {
                ValueSet message = new ValueSet();
                message.Add(Constant.BackgroundTaskStarted, "");
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }  
            Playlist.TrackChanged += Playlist_TrackChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            BackgroundMediaPlayer.Current.MediaEnded +=Current_MediaEnded;
            ApplicationSettingHelper.SaveSettingsValue(Constant.BackgroundTaskState, Constant.BackgroundTaskRunning);
            isbackgroundtaskrunning = true;
            _loopState = eLoopState.None;
        }
Exemplo n.º 9
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Enable system transport controls for the current view. 
            _systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
            _systemMediaTransportControl.IsEnabled = true;
            _systemMediaTransportControl.IsPauseEnabled = true;
            _systemMediaTransportControl.IsPlayEnabled = true;
            _systemMediaTransportControl.ButtonPressed += MediaTransportControlButtonPressed;
            
            // Handle events
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;
            BackgroundMediaPlayer.Current.BufferingStarted += Current_BufferingStarted;
            BackgroundMediaPlayer.Current.MediaFailed += Current_MediaFailed;

            // Handle the closing of the background task correctly
            taskInstance.Canceled += taskInstance_Canceled;
            taskInstance.Task.Completed += Task_Completed;

            _deferral = taskInstance.GetDeferral();

            // TODO: load _nowPlaying from app settings
            if (ApplicationData.Current.LocalSettings.Values.ContainsKey("CurrentStation"))
            {
                _nowPlaying = ApplicationData.Current.LocalSettings.Values["CurrentStation"].ToString();
                //ApplicationData.Current.LocalSettings.Values.Remove("NowPlaying");
            }

            _BackgroundStarted.Set();
            _isBackgroundTaskRunning = true;
            // END

            Debug.WriteLine("BackgroundAudioTask - Started");
        }
Exemplo n.º 10
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            mediaTransportControls = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            mediaTransportControls.ButtonPressed += MediaButtonPressed;
            mediaTransportControls.PropertyChanged += MediaPropertyChanged;
            mediaTransportControls.IsEnabled = true;
            mediaTransportControls.IsPauseEnabled = true;
            mediaTransportControls.IsPlayEnabled = true;
            mediaTransportControls.IsNextEnabled = true;
            mediaTransportControls.IsPreviousEnabled = true;

            BackgroundMediaPlayer.Current.CurrentStateChanged += MediaPlayerStateChanged;

            messageTransport.PlaybackRequested += OnPlaybackRequested;

            messageTransport.Start();
            messageTransport.NotifyForeground();

            deferral = taskInstance.GetDeferral();

            backgroundTaskStarted.Set();

            taskInstance.Task.Completed += TaskCompleted;
            taskInstance.Canceled += OnCanceled;
        }
Exemplo n.º 11
0
 private void MediaButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
 {
     switch (args.Button)
     {
         case SystemMediaTransportControlsButton.Play:
             BackgroundMediaPlayer.SendMessageToForeground(new ValueSet
             {
                 {"command", PlaybackCommand.Play.ToString()}
             });
             break;
         case SystemMediaTransportControlsButton.Pause:
         case SystemMediaTransportControlsButton.Stop:
             BackgroundMediaPlayer.SendMessageToForeground(new ValueSet
             {
                 {"command", PlaybackCommand.Pause.ToString()}
             });
             break;
         case SystemMediaTransportControlsButton.Previous:
             BackgroundMediaPlayer.SendMessageToForeground(new ValueSet
             {
                 {"command", PlaybackCommand.Previous.ToString()}
             });
             break;
         case SystemMediaTransportControlsButton.Next:
             BackgroundMediaPlayer.SendMessageToForeground(new ValueSet
             {
                 {"command", PlaybackCommand.Next.ToString()}
             });
             break;
     }
 }
Exemplo n.º 12
0
        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.systemControls = SystemMediaTransportControls.GetForCurrentView();
            this.systemControls.ButtonPressed += systemControls_ButtonPressed;
            this.systemControls.IsPlayEnabled = true;
            this.systemControls.IsPauseEnabled = true;

            this.renderer = await AudioRenderer.CreateAsync();

            var rootPath = Windows.ApplicationModel.Package.Current.InstalledLocation.Path + "\\Sounds\\";
            this.drumPad = new DrumPad();
            this.drumPad.SetDrumSound(DrumKind.Bass, rootPath + "Drum-Bass.wav");
            this.drumPad.SetDrumSound(DrumKind.Snare, rootPath + "Drum-Snare.wav");
            this.drumPad.SetDrumSound(DrumKind.Shaker, rootPath + "Drum-Shaker.wav");
            this.drumPad.SetDrumSound(DrumKind.ClosedHiHat, rootPath + "Drum-Closed-Hi-Hat.wav");
            this.drumPad.SetDrumSound(DrumKind.Cowbell, rootPath + "Cowbell.wav");
            this.drumPad.SetDrumSound(DrumKind.OpenHiHat, rootPath + "Drum-Open-Hi-Hat.wav");
            this.drumPad.SetDrumSound(DrumKind.RideCymbal, rootPath + "Drum-Ride-Cymbal.wav");
            this.drumPad.SetDrumSound(DrumKind.FloorTom, rootPath + "developer_loud.wav");
            this.drumPad.SetDrumSound(DrumKind.HighTom, rootPath + "satya_fantastic.wav");

            this.oscillator = new Oscillator();
            this.looper = new Looper();
            this.demultiplexer = new AudioDemultiplexer();

            this.looper.ListenTo(this.drumPad);
            this.demultiplexer.ListenTo(this.looper);
            this.demultiplexer.ListenTo(this.oscillator);
            this.renderer.ListenTo(this.demultiplexer);

            Play();
        }
        public MainPage()
        {
            this.InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Enabled;

            // Register for the window resize event
            Window.Current.SizeChanged += WindowSizeChanged;

            // Source for WebControl || XAML
            songInformation.Source = new Uri("ms-appx-web:///HTML code/SongInformation.html");
            previousSongInformation.Source = new Uri("ms-appx-web:///HTML code/PreviousSongs_Larger.html");
            MenuWebView.Navigate(new Uri("http://vocaloidradio.com/"));
            currentPage.Text = "Vocaloid Radio";

            // Hook up app to system transport controls.
            mediaControl = SystemMediaTransportControls.GetForCurrentView();
            mediaControl.ButtonPressed += medialControl_ButtonPressed;

            // Register to handle the following system transpot control buttons.
            mediaControl.IsPlayEnabled = true;
            mediaControl.IsPauseEnabled = true;
            mediaControl.IsFastForwardEnabled = false;
            mediaControl.IsNextEnabled = false;
            mediaControl.IsPreviousEnabled = false;
            mediaControl.IsRewindEnabled = false;
            mediaControl.IsChannelDownEnabled = false;
            mediaControl.IsChannelUpEnabled = false;
            mediaControl.IsRecordEnabled = false;
            
            
        }
Exemplo n.º 14
0
        /// <summary>
        /// The Run method is the entry point of a background task. 
        /// </summary>
        /// <param name="taskInstance"></param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");
                // Initialize SMTC object to talk with UVC. 
                //Note that, this is intended to run after app is paused and 
                //hence all the logic must be written to run in background process
                systemmediatransportcontrol = SystemMediaTransportControls.GetForCurrentView();
                systemmediatransportcontrol.ButtonPressed += systemmediatransportcontrol_ButtonPressed;
                systemmediatransportcontrol.PropertyChanged += systemmediatransportcontrol_PropertyChanged;
                systemmediatransportcontrol.IsEnabled = true;
                systemmediatransportcontrol.IsPauseEnabled = true;
                systemmediatransportcontrol.IsPlayEnabled = true;
                systemmediatransportcontrol.IsNextEnabled = true;
                systemmediatransportcontrol.IsPreviousEnabled = true;

                // Associate a cancellation and completed handlers with the background task.
                taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
                taskInstance.Task.Completed += Taskcompleted;

                var value = ApplicationSettingsHelper.ReadResetSettingsValue(BackgroundAudioConstants.AppState);
                if (value == null)
                    foregroundAppState = ForegroundAppStatus.Unknown;
                else
                    foregroundAppState = (ForegroundAppStatus)Enum.Parse(typeof(ForegroundAppStatus), value.ToString());

                //Add handlers for MediaPlayer
                BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;

                //Add handlers for playlist trackchanged
                Playlist.TrackChanged += playList_TrackChanged;

                //Initialize message channel 
                BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;

                //Send information to foreground that background task has been started if app is active
                if (foregroundAppState != ForegroundAppStatus.Suspended)
                {
                    ValueSet message = new ValueSet();
                    message.Add(BackgroundAudioConstants.BackgroundTaskStarted, "");
                    BackgroundMediaPlayer.SendMessageToForeground(message);
                }
                BackgroundTaskStarted.Set();
                backgroundtaskrunning = true;

                Playlist.PopulatePlaylist();
                var currentTrackIndex = ApplicationSettingsHelper.ReadSettingsValue(BackgroundAudioConstants.CurrentTrack);
                if (currentTrackIndex != null)
                {
                    Playlist.CurrentTrack = (int)currentTrackIndex;
                }
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.BackgroundTaskState, BackgroundAudioConstants.BackgroundTaskRunning);
                deferral = taskInstance.GetDeferral();
            }
            catch
            {
            }
        }
Exemplo n.º 15
0
 public MediaTransportService(SystemMediaTransportControls smtc)
 {
     _smtc = smtc;
     PlaybackStatus = MediaPlaybackStatus.Closed;
     _smtc.DisplayUpdater.Type = MediaPlaybackType.Music;
     _smtc.DisplayUpdater.Update();
     _smtc.ButtonPressed += _smtc_ButtonPressed;
 }
 private void RegisterSystemMediaTransportControlsEvents()
 {
     smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
     smtc.IsEnabled = true;
     smtc.IsPauseEnabled = true;
     smtc.IsStopEnabled = true;
     smtc.IsPlayEnabled = true;
     smtc.ButtonPressed += OnButtonPressed;
 }
        private void InitializeSystemMediaControls()
        {
            systemPlayerControls = SystemMediaTransportControls.GetForCurrentView();

            systemPlayerControls.ButtonPressed += SystemControls_ButtonPressed;

            systemPlayerControls.IsPlayEnabled = true;
            systemPlayerControls.IsPauseEnabled = true;
        }
Exemplo n.º 18
0
 public SmtcWrapper(SystemMediaTransportControls smtc)
 {
     _smtc = smtc;
     smtc.IsEnabled = true;
     smtc.IsPauseEnabled = true;
     smtc.IsPlayEnabled = true;
     smtc.IsNextEnabled = true;
     smtc.IsPreviousEnabled = true;
     Subscribe();
 }
 private void InitializeAndSetMediaTransportControl()
 {
     _systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
     _systemMediaTransportControl.ButtonPressed += systemMediaTransportControl_ButtonPressed;
     _systemMediaTransportControl.PropertyChanged += systemMediaTransportControl_PropertyChanged;
     _systemMediaTransportControl.IsEnabled = true;
     _systemMediaTransportControl.IsPauseEnabled = true;
     _systemMediaTransportControl.IsPlayEnabled = true;
     _systemMediaTransportControl.IsNextEnabled = true;
     _systemMediaTransportControl.IsPreviousEnabled = true;
 }
Exemplo n.º 20
0
        //=========Methode
        public PageAcceuil()
        {
            this.InitializeComponent();
            systemControls = SystemMediaTransportControls.GetForCurrentView();
            systemControls.ButtonPressed += SystemControls_ButtonPressed;
            MyControlMusic.CurrentStateChanged += MediaElement_CurrentStateChanged;
            systemControls.IsPlayEnabled = true;
            systemControls.IsPauseEnabled = true;
            

    }
Exemplo n.º 21
0
 /// <summary>
 ///     Handle the buttons on the Universal Volume Control
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private void MediaTransportControlButtonPressed(SystemMediaTransportControls sender,
     SystemMediaTransportControlsButtonPressedEventArgs args)
 {
     switch (args.Button)
     {
         case SystemMediaTransportControlsButton.Play:
             BackgroundMediaPlayer.Current.Play();
             break;
         case SystemMediaTransportControlsButton.Pause:
             BackgroundMediaPlayer.Current.Pause();
             break;
     }
 }
        public PlaybackControl()
        {
            this.InitializeComponent();

            // add new handlers
            systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            systemMediaControls.PropertyChanged += SystemMediaControls_PropertyChanged;
            systemMediaControls.ButtonPressed += SystemMediaControls_ButtonPressed;
            systemMediaControls.IsPlayEnabled = true;
            systemMediaControls.IsPauseEnabled = true;
            systemMediaControls.IsStopEnabled = true;
            systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
        }
        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();
        }
Exemplo n.º 24
0
 public void Register()
 {
     _eventAggregator.Subscribe(this);
     _mediaTransportControls = SystemMediaTransportControls.GetForCurrentView();
     _mediaTransportControls.DisplayUpdater.AppMediaId = "Subsonic8";
     _mediaTransportControls.IsPlayEnabled = true;
     _mediaTransportControls.IsPauseEnabled = true;
     _mediaTransportControls.IsStopEnabled = true;
     _mediaTransportControls.IsNextEnabled = true;
     _mediaTransportControls.IsPreviousEnabled = true;
     _mediaTransportControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
     _mediaTransportControls.ButtonPressed += MediaTransportControlsOnButtonPressed;
 }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Handle events from system transport contrtols when playing background-capable media
            systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            systemMediaControls.ButtonPressed += SystemMediaControls_ButtonPressed;
            systemMediaControls.IsPlayEnabled = true;
            systemMediaControls.IsPauseEnabled = true;
            systemMediaControls.IsStopEnabled = true;

            rootPage.SystemMediaTransportControlsInitialized = true;

            Scenario6MediaElement.CurrentStateChanged += MediaElement_CurrentStateChanged;
        }
Exemplo n.º 26
0
        public MainPage()
        {
            InitializeComponent();

            MediaControls = SystemMediaTransportControls.GetForCurrentView();

            MediaControls.IsNextEnabled = true;
            MediaControls.IsPreviousEnabled = true;

            MediaControls.IsFastForwardEnabled = true;
            MediaControls.IsRewindEnabled = true;

            //MediaControls.ButtonPressed += MediaControls_ButtonPressed;
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            _systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
            _systemMediaTransportControl.IsEnabled = true;

            BackgroundMediaPlayer.MessageReceivedFromForeground += MessageReceivedFromForeground;
            BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayerCurrentStateChanged;

            // Associate a cancellation and completed handlers with the background task.
            taskInstance.Canceled += OnCanceled;
            taskInstance.Task.Completed += Taskcompleted;

            _deferral = taskInstance.GetDeferral();
        }
Exemplo n.º 28
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Logger.Current.Init(LogType.AudioFunction);

            PlayQueueManager.Current.Connect();

            systemMediaTransportControls = SystemMediaTransportControls.GetForCurrentView();
            systemMediaTransportControls.ButtonPressed += HandleSystemMediaTransportControlsButtonPressed;
            systemMediaTransportControls.PropertyChanged += HandleSystemMediaTransportControlsPropertyChanged;
            systemMediaTransportControls.IsEnabled = true;
            systemMediaTransportControls.IsPauseEnabled = true;
            systemMediaTransportControls.IsPlayEnabled = true;
            systemMediaTransportControls.IsNextEnabled = true;
            systemMediaTransportControls.IsPreviousEnabled = true;

            taskInstance.Canceled += HandleTaskInstanceCanceled;
            taskInstance.Task.Completed += HandleTaskInstanceTaskCompleted;
            taskInstance.Task.Progress += Task_Progress;

            BackgroundMediaPlayer.Current.CurrentStateChanged += HandleBackgroundMediaPlayerCurrentStateChanged;
            BackgroundMediaPlayer.Current.SeekCompleted += HandleBackgroundMediaPlayerSeekComplete;
            BackgroundMediaPlayer.MessageReceivedFromForeground += HandleBackgroundMediaPlayerMessageReceivedFromForeground;

            backgroundTaskStarted.Set();
            backgroundTaskState = BackgroundTaskState.Running;

            backgroundTaskDefferal = taskInstance.GetDeferral();

            PlayQueueManager.Current.TrackChanged += HandlePlayQueueTrackChanged;

            ApplicationSettings.PutSettingsValue(ApplicationSettings.IS_BACKGROUND_PROCESS_ACTIVE, true);

            if (ApplicationSettings.GetSettingsValue<bool>(ApplicationSettings.IS_FOREGROUND_PROCESS_ACTIVE, false))
            {
                Logger.Current.Init(LogType.AudioFunction);

                Logger.Current.Log(new CallerInfo(), LogLevel.Info, "Sending message to the FG -- BackgroundStarted");

                PlayQueueManager.Current.SendMessageToForeground(PlayQueueConstantBGMessageId.BackgroundStarted);
                foregroundTaskState = ForegroundTaskState.Running;
            }
            else
            {
                Logger.Current.Init(LogType.AudioFunction);

                Logger.Current.Log(new CallerInfo(), LogLevel.Info, "Didn't send message to the FG because FG not started");

                foregroundTaskState = ForegroundTaskState.Stopped;
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Creates new instance of <see cref="AudioManager"/>
 /// </summary>
 /// <param name="logger">The logger instance</param>
 /// <param name="applicationSettingsHelper">The application settings helper instance</param>
 /// <param name="smtc">Instance of <see cref="SystemMediaTransportControls"/></param>
 public AudioManager(
     ILogger logger,
     IApplicationSettingsHelper applicationSettingsHelper,
     SystemMediaTransportControls smtc)
 {
     this.logger = logger;
     this.applicationSettingsHelper = applicationSettingsHelper;
     this.smtc = smtc;
     logger.LogMessage("Initializing Background Audio Manager...");
     setupSmtc();
     subscribeToMediaEvents();
     playlistLoading = new TaskCompletionSource<bool>();
     playlistLoading.SetResult(true);
     logger.LogMessage("BackgroundAudio: Background Audio Manager has been initialized.", LoggingLevel.Information);
 }
Exemplo n.º 30
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     
     BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
     mediaplayer.CurrentStateChanged += Mediaplayer_CurrentStateChanged;
     taskInstance.Canceled += TaskInstance_Canceled;
     stmp = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
     stmp.ButtonPressed += Stmp_ButtonPressed;
     stmp.IsEnabled = true;
     stmp.IsPauseEnabled = true;
     stmp.IsPlayEnabled = true;
     stmp.IsNextEnabled = true;
     stmp.IsPreviousEnabled = true;
     _deferral = taskInstance.GetDeferral();
 }
Exemplo n.º 31
0
        public static async void Init(CoreDispatcher dispatcher)
        {
            _dispatcher = dispatcher;

            var mediaControls = SystemMediaTransportControls.GetForCurrentView();

            mediaControls.IsEnabled         = true;
            mediaControls.IsPreviousEnabled = true;
            mediaControls.IsNextEnabled     = true;
            mediaControls.IsPlayEnabled     = true;
            mediaControls.IsPauseEnabled    = true;
            mediaControls.PlaybackStatus    = MediaPlaybackStatus.Paused;
            mediaControls.ButtonPressed    += SystemControls_ButtonPressed;
            await mediaControls.DisplayUpdater.CopyFromFileAsync(MediaPlaybackType.Music,
                                                                 await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Media/silent.wav")));

            MediaControls = mediaControls;

            PlayStatusTracker.LastPlayStatus.Updated += LastPlayStatus_Updated;
        }
Exemplo n.º 32
0
 /// <summary>
 /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
 /// notification, it is no longer in the foregroud.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private async void SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args)
 {
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
     {
         // Only handle this event if this page is currently being displayed
         if (args.Property == SystemMediaTransportControlsProperty.SoundLevel && Frame.CurrentSourcePageType == typeof(MainPage))
         {
             // Check to see if the app is being muted. If so, it is being minimized.
             // Otherwise if it is not initialized, it is being brought into focus.
             if (sender.SoundLevel == SoundLevel.Muted)
             {
                 await CleanupCameraAsync();
             }
             else if (!_isInitialized)
             {
                 await InitializeCameraAsync();
             }
         }
     });
 }
Exemplo n.º 33
0
        /// <summary>
        /// 处理UVC产生的按键事件
        /// </summary>
        /// <remarks>如果这段代码不运行在后台进程,则当其挂起时无法响应UVC事件</remarks>
        private void smtc_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Play:
                DebugWrite("UVC play button pressed", "BackgroundPlayer");

                // 后台任务挂起后SMTC会异步启动,有时需要让在Run()中的启动过程完成

                // 等待后台任务开始。一旦开始后,保持信号直到被关闭,使得不用再次等待,除非其他需要
                bool result = backgroundTaskStarted.WaitOne(5000);
                if (!result)
                {
                    throw new Exception("Background Task didn't initialize in time");
                }
                StartPlayback();
                break;

            case SystemMediaTransportControlsButton.Pause:
                DebugWrite("UVC pause button pressed", "BackgroundPlayer");
                try
                {
                    BackgroundMediaPlayer.Current.Pause();
                }
                catch (Exception ex)
                {
                    ErrorWrite(ex, "BackgroundPlayer");
                }
                break;

            case SystemMediaTransportControlsButton.Next:
                DebugWrite("UVC next button pressed", "BackgroundPlayer");
                MessageService.SendMediaMessageToForeground(MediaMessageTypes.SkipNext);
                break;

            case SystemMediaTransportControlsButton.Previous:
                DebugWrite("UVC previous button pressed", "BackgroundPlayer");
                MessageService.SendMediaMessageToForeground(MediaMessageTypes.SkipPrevious);
                break;
            }
        }
Exemplo n.º 34
0
        private async void SystemControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Play:
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    userimage.IsChecked = false;
                    var vs = new ValueSet();
                    vs.Add("state", "play");
                    try
                    {
                        BackgroundMediaPlayer.SendMessageToBackground(vs);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                });

                break;

            case SystemMediaTransportControlsButton.Pause:
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    userimage.IsChecked = true;
                    var vs = new ValueSet();
                    vs.Add("state", "pause");
                    try
                    {
                        BackgroundMediaPlayer.SendMessageToBackground(vs);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                });

                break;
            }
        }
Exemplo n.º 35
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");

            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed    += smtc_ButtonPressed;
            smtc.PropertyChanged  += smtc_PropertyChanged;
            smtc.IsEnabled         = true;
            smtc.IsPauseEnabled    = true;
            smtc.IsPlayEnabled     = true;
            smtc.IsNextEnabled     = true;
            smtc.IsPreviousEnabled = true;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);

            if (value == null)
            {
                foregroundAppState = AppState.Unknow;
            }
            else
            {
                foregroundAppState = (AppState)value;
            }

            BackgroundMediaPlayer.Current.CurrentStateChanged   += Current_CurrentStateChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;

            if (foregroundAppState != AppState.Suspended)
            {
                MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());
            }

            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running);

            deferral = taskInstance.GetDeferral();

            backgroundTaskStarted.Set();

            taskInstance.Task.Completed += Task_Completed;
            taskInstance.Canceled       += new BackgroundTaskCanceledEventHandler(OnCanceled);
        }
Exemplo n.º 36
0
        private async void TransportControlsButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            if (args.Button.Equals(SystemMediaTransportControlsButton.Play))
            {
                await RunOnUiThread(this.Play);

                return;
            }

            if (args.Button.Equals(SystemMediaTransportControlsButton.Pause))
            {
                await RunOnUiThread(this.Pause);

                return;
            }

            if (args.Button.Equals(SystemMediaTransportControlsButton.Stop))
            {
                await RunOnUiThread(this.Stop);
            }
        }
Exemplo n.º 37
0
        private void MediaTransportButtonClik(SystemMediaTransportControls transportControls, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Play:
                Play();
                break;

            case SystemMediaTransportControlsButton.Pause:
                Pause();
                break;

            case SystemMediaTransportControlsButton.Next:
                PlayNext();
                break;

            case SystemMediaTransportControlsButton.Previous:
                PlayPrev();
                break;
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Handles a request from the System Media Transport Controls to change our current playback position.
        /// </summary>
        private async void systemMediaControls_PlaybackPositionChangeRequested(SystemMediaTransportControls sender, PlaybackPositionChangeRequestedEventArgs args)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                // First we validate that the requested position falls within the range of the current piece of content we are playing,
                // this should usually be the case but the content may have changed whilst the request was coming in.
                if (args.RequestedPlaybackPosition.Duration() <= mediaPlayer.PlaybackSession.NaturalDuration.Duration() &&
                    args.RequestedPlaybackPosition.Duration().TotalSeconds >= 0)
                {
                    // Next we verify that our player is in a state that we think is valid to change the position
                    if (mediaPlayer.PlaybackSession.PlaybackState == MediaPlaybackState.Paused || mediaPlayer.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
                    {
                        // Finally if the above conditions are met we update the position and report the new position back to SMTC.
                        mediaPlayer.PlaybackSession.Position = args.RequestedPlaybackPosition.Duration();
                        UpdateSmtcPosition();
                    }
                }

                rootPage.NotifyUser("Playback position change requested", NotifyType.StatusMessage);
            });
        }
Exemplo n.º 39
0
        public void SetTransportControls(SystemMediaTransportControls transportControls)
        {
            if (controls != null)
            {
                controls.IsEnabled = false;
                controls.PlaybackPositionChangeRequested -= OnSeekTo;
                controls.ButtonPressed -= OnButtonPressed;
            }

            controls = transportControls;

            if (controls != null)
            {
                controls.IsEnabled = true;

                controls.PlaybackPositionChangeRequested += OnSeekTo;
                controls.ButtonPressed += OnButtonPressed;

                UpdateCapabilities();
            }
        }
Exemplo n.º 40
0
        async void OnMediaButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs e)
        {
            if (e.Button == SystemMediaTransportControlsButton.Pause ||
                e.Button == SystemMediaTransportControlsButton.Stop)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Low, new DispatchedHandler(() =>

                {
                    mediaElement.Source = null;
                    var smtc = SystemMediaTransportControls.GetForCurrentView();
                    smtc.PlaybackStatus = MediaPlaybackStatus.Closed;
                }));
            }
            else if (e.Button == SystemMediaTransportControlsButton.Play)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.High, new DispatchedHandler(() =>
                {
                }
                                                                                             ));
            }
        }
Exemplo n.º 41
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            FolderMusicUwpLib.SaveTextClass.SetId(taskInstance.InstanceId.ToString());
            FolderMusicUwpLib.SaveTextClass.SaveText("Run");

            task = this;

            lastTicks = DateTime.Now.Ticks;

            ForegroundCommunicator.SetReceivedEvent();

            systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
            deferral = taskInstance.GetDeferral();

            ActivateSystemMediaTransportControl();
            systemMediaTransportControl.ButtonPressed += MediaTransportControlButtonPressed;

            SetEvents(taskInstance);

            LoadCurrentSongAndLibrary();
        }
Exemplo n.º 42
0
        private void transportControl_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Play:
                // If music is in paused state, for a period of more than 5 minutes,
                //app will get task cancellation and it cannot run code.
                //However, user can still play music by pressing play via UVC unless a new app comes in clears UVC.
                //When this happens, the task gets re-initialized and that is asynchronous and hence the wait
                if (!backgroundTaskRunning)
                {
                    bool result = backgroundTaskStarted.WaitOne(2000);
                    if (!result)
                    {
                        throw new Exception(SharedStrings.BACKGROUND_AUDIO_STARTUP_TIMEOUT);
                    }
                }
                StartPlayback();
                break;

            case SystemMediaTransportControlsButton.Pause:
                try
                {
                    BackgroundMediaPlayer.Current.Pause();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("CoffeeBackgroundAudioTask.transportControl_ButtonPressed: " + ex.ToString());
                }
                break;

            case SystemMediaTransportControlsButton.Next:
                SkipToNext();
                break;

            case SystemMediaTransportControlsButton.Previous:
                SkipToPrevious();
                break;
            }
        }
Exemplo n.º 43
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed    += OnSmtcButtonPressed;
            smtc.PropertyChanged  += OnSmtcPropertyChanged;
            smtc.IsEnabled         = true;
            smtc.IsPauseEnabled    = true;
            smtc.IsPlayEnabled     = true;
            smtc.IsNextEnabled     = true;
            smtc.IsPreviousEnabled = true;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);

            if (value == null)
            {
                foregroundAppState = AppState.Unknown;
            }
            else
            {
                foregroundAppState = EnumHelper.Parse <AppState>(value.ToString());
            }

            BackgroundMediaPlayer.Current.CurrentStateChanged   += OnMediaPlayerCurrentStateChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += OnMessageFromForegroundReceived;

            if (foregroundAppState != AppState.Suspended)
            {
                MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());
            }

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

            deferral = taskInstance.GetDeferral();

            backgroundTaskStarted.Set();

            taskInstance.Task.Completed += (s, a) => deferral.Complete();
            taskInstance.Canceled       += new BackgroundTaskCanceledEventHandler(OnCanceled);
        }
Exemplo n.º 44
0
        private void _smtc_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            try
            {
                switch (args.Button)
                {
                case Windows.Media.SystemMediaTransportControlsButton.Play:
                    mediaplayer.Play();
                    {
                        ValueSet vs = new ValueSet();
                        vs.Add("Play", "Playing");
                        BackgroundMediaPlayer.SendMessageToForeground(vs);
                    }
                    //_smtc.IsPlayEnabled = false;
                    //_smtc.IsPauseEnabled = true;
                    _smtc.PlaybackStatus = MediaPlaybackStatus.Playing;
                    break;

                case Windows.Media.SystemMediaTransportControlsButton.Pause:
                    mediaplayer.Pause();
                    {
                        ValueSet vs = new ValueSet();
                        vs.Add("Play", "Paused");
                        BackgroundMediaPlayer.SendMessageToForeground(vs);
                    }
                    _smtc.PlaybackStatus = MediaPlaybackStatus.Paused;
                    // _smtc.IsPlayEnabled = true;
                    //_smtc.IsPauseEnabled = false;
                    break;

                default:
                    break;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 45
0
        public TalkPage()
        {
            this.InitializeComponent();
            synth = new SpeechSynthesizer();

            appVersion.Text = UpdateHelper.GetVersion();
            CheckUpdateStatus();
            GetVoices();
            CheckPurchaseStatus();

            _loopEnabled = false;

            _player.AutoPlay              = false;
            _player.AudioCategory         = MediaPlayerAudioCategory.Speech;
            _mediaControls                = _player.SystemMediaTransportControls;
            _mediaControls.AutoRepeatMode = MediaPlaybackAutoRepeatMode.None;
            txtTextToSay.Focus(FocusState.Programmatic);

            var titleBar = CoreApplication.GetCurrentView().TitleBar;

            titleBar.IsVisibleChanged += TitleBar_IsVisibleChanged;
        }
Exemplo n.º 46
0
        private void PluginStartUp()
        {
            // set up media player to get manual control of SystemMediaTransportControls
            mediaPlayer = new MediaPlayer();
            mediaPlayer.CommandManager.IsEnabled = false;

            // set up SystemMediaTransportControls
            systemMediaControls = mediaPlayer.SystemMediaTransportControls;
            // set flags
            systemMediaControls.PlaybackStatus       = MediaPlaybackStatus.Closed; // nothing in list to play
            systemMediaControls.IsEnabled            = true;                       // show it
            systemMediaControls.IsPlayEnabled        = true;
            systemMediaControls.IsPauseEnabled       = true;
            systemMediaControls.IsStopEnabled        = true;
            systemMediaControls.IsPreviousEnabled    = true;
            systemMediaControls.IsNextEnabled        = true;
            systemMediaControls.IsRewindEnabled      = true;
            systemMediaControls.IsFastForwardEnabled = false;

            // Sync musicbee volume with Windows volume
            //mbApiInterface.Player_SetVolume() = systemMediaControls.SoundLevel

            systemMediaControls.ButtonPressed += systemMediaControls_ButtonPressed;
            systemMediaControls.PlaybackPositionChangeRequested +=
                systemMediaControls_PlaybackPositionChangeRequested;
            systemMediaControls.PlaybackRateChangeRequested   += systemMediaControls_PlaybackRateChangeRequested;
            systemMediaControls.ShuffleEnabledChangeRequested +=
                systemMediaControls_ShuffleEnabledChangeRequested;
            systemMediaControls.AutoRepeatModeChangeRequested +=
                systemMediaControls_AutoRepeatModeChangeRequested;

            // setup overlay properties
            displayUpdater            = systemMediaControls.DisplayUpdater;
            displayUpdater.Type       = MediaPlaybackType.Music; // media type
            displayUpdater.AppMediaId = "MusicBee";              // program name
            // setup for display music properties on overlay
            musicProperties = displayUpdater.MusicProperties;
            SetDisplayValues();
        }
Exemplo n.º 47
0
        private void OnButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Play:
                bool result = backgroundTaskStarted.WaitOne(5000);
                if (!result)
                {
                    return;
                }
                StartPlayback();
                break;

            case SystemMediaTransportControlsButton.Pause:
                BackgroundMediaPlayer.Current.Pause();
                break;

            case SystemMediaTransportControlsButton.Stop:
                BackgroundMediaPlayer.Shutdown();
                break;
            }
        }
Exemplo n.º 48
0
        public PlaybackService(IProtoService protoService, ICacheService cacheService, ISettingsService settingsService, IEventAggregator aggregator)
        {
            if (!ApiInfo.IsMediaSupported)
            {
                return;
            }

            _protoService    = protoService;
            _cacheService    = cacheService;
            _settingsService = settingsService;
            _aggregator      = aggregator;

            _mediaPlayer = new MediaPlayer();
            _mediaPlayer.PlaybackSession.PlaybackStateChanged += OnPlaybackStateChanged;
            _mediaPlayer.PlaybackSession.PositionChanged      += OnPositionChanged;
            _mediaPlayer.MediaFailed             += OnMediaFailed;
            _mediaPlayer.MediaEnded              += OnMediaEnded;
            _mediaPlayer.SourceChanged           += OnSourceChanged;
            _mediaPlayer.CommandManager.IsEnabled = false;
            _mediaPlayer.Volume = _settingsService.VolumeLevel;

            _transport = _mediaPlayer.SystemMediaTransportControls;
            _transport.ButtonPressed += Transport_ButtonPressed;

            _transport.AutoRepeatMode = _settingsService.Playback.RepeatMode;
            _isRepeatEnabled          = _settingsService.Playback.RepeatMode == MediaPlaybackAutoRepeatMode.Track
                ? null
                : _settingsService.Playback.RepeatMode == MediaPlaybackAutoRepeatMode.List
                ? true
                : (bool?)false;

            _mapping = new Dictionary <string, PlaybackItem>();

            aggregator.Subscribe(this);

            _watcher        = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher(ProximitySensor.GetDeviceSelector());
            _watcher.Added += OnProximitySensorAdded;
            _watcher.Start();
        }
Exemplo n.º 49
0
        private static async void _smtc_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1))
            {
                //we do not want to pause the background player.
                //pausing may cause stutter, that's why.
                _player?.Play();
            }
            await BreadDispatcher.InvokeAsync(() =>
            {
                switch (args.Button)
                {
                case SystemMediaTransportControlsButton.Play:
                case SystemMediaTransportControlsButton.Pause:
                    Messenger.Instance.NotifyColleagues(MessageTypes.MsgExecuteCmd, "PlayPause");
                    break;

                case SystemMediaTransportControlsButton.Next:
                    Messenger.Instance.NotifyColleagues(MessageTypes.MsgExecuteCmd, "PlayNext");
                    break;

                case SystemMediaTransportControlsButton.Previous:
                    Messenger.Instance.NotifyColleagues(MessageTypes.MsgExecuteCmd, "PlayPrevious");
                    break;

                case SystemMediaTransportControlsButton.FastForward:
                    Messenger.Instance.NotifyColleagues(MessageTypes.MsgExecuteCmd, "SeekForward");
                    break;

                case SystemMediaTransportControlsButton.Rewind:
                    Messenger.Instance.NotifyColleagues(MessageTypes.MsgExecuteCmd, "SeekBackward");
                    break;

                default:
                    break;
                }
            });
        }
        /// <summary>
        /// 按下系统音乐控制器按钮的event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void Smtc_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Play:
                Debug.WriteLine("UVC play button pressed");

                bool result = backgroundTaskStarted.WaitOne(5000);
                if (!result)
                {
                    throw new Exception("Background Tast didn't initialize in time");
                }
                StartPlayback();
                break;

            case SystemMediaTransportControlsButton.Pause:
                Debug.WriteLine("UVC pause button pressed");
                try
                {
                    BackgroundMediaPlayer.Current.Pause();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString() + " " + ex.Message);
                }
                break;

            case SystemMediaTransportControlsButton.Next:
                Debug.WriteLine("UVC next button pressed");
                SkipToNext();
                break;

            case SystemMediaTransportControlsButton.Previous:
                Debug.WriteLine("UVC previous button pressed");
                SkipToPrevious();
                break;
            }
        }
Exemplo n.º 51
0
        private void Player_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            if (Winamp.Status == Status.Stopped)
            {
                Winamp.Play();
                return;
            }
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Pause:
            case SystemMediaTransportControlsButton.Play:
                Winamp.PlayPause();
                break;

            case SystemMediaTransportControlsButton.Next:
                Winamp.NextTrack();
                break;

            case SystemMediaTransportControlsButton.Previous:
                Winamp.PreviousTrack();
                break;
            }
        }
Exemplo n.º 52
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Debug.WriteLine("MainPage.OnNavigatedTo()");

            base.OnNavigatedTo(e);

            var smtc = SystemMediaTransportControls.GetForCurrentView();

            smtc.PlaybackStatus = MediaPlaybackStatus.Closed;

            UpdateTrack(smtc);

            smtc.ButtonPressed += SystemControls_ButtonPressed;

            smtc.IsPlayEnabled  = true;
            smtc.IsPauseEnabled = true;
            smtc.IsStopEnabled  = true;

            var multipleTracks = _tracks.Count > 1;

            smtc.IsNextEnabled     = multipleTracks;
            smtc.IsPreviousEnabled = false;
        }
Exemplo n.º 53
0
 public static void InitializeHyPlaylist()
 {
     Player = new MediaPlayer()
     {
         AutoPlay         = true,
         IsLoopingEnabled = false
     };
     MediaSystemControls                   = SystemMediaTransportControls.GetForCurrentView();
     ControlsDisplayUpdater                = MediaSystemControls.DisplayUpdater;
     Player.CommandManager.IsEnabled       = false;
     MediaSystemControls.IsPlayEnabled     = true;
     MediaSystemControls.IsPauseEnabled    = true;
     MediaSystemControls.IsNextEnabled     = true;
     MediaSystemControls.IsPreviousEnabled = true;
     MediaSystemControls.IsEnabled         = false;
     MediaSystemControls.ButtonPressed    += SystemControls_ButtonPressed;
     MediaSystemControls.PlaybackStatus    = MediaPlaybackStatus.Closed;
     Player.SourceChanged                 += Player_SourceChanged;
     Player.MediaEnded                      += Player_MediaEnded;
     Player.CurrentStateChanged             += Player_CurrentStateChanged;
     Player.VolumeChanged                   += Player_VolumeChanged;
     Player.PlaybackSession.PositionChanged += PlaybackSession_PositionChanged;
 }
Exemplo n.º 54
0
        void UpdateState(MediaElementState state)
        {
            var smtc = SystemMediaTransportControls.GetForCurrentView();

            if (state == MediaElementState.Closed)
            {
                // play enabled, stop not enabled
                smtc.PlaybackStatus = MediaPlaybackStatus.Closed;
            }
            else if (state == MediaElementState.Playing)
            {
                // play not enabled, stop enabled
                smtc.PlaybackStatus = MediaPlaybackStatus.Playing;
            }
            else if (state == MediaElementState.Paused)
            {
                smtc.PlaybackStatus = MediaPlaybackStatus.Paused;
            }
            else if (state == MediaElementState.Stopped)
            {
                smtc.PlaybackStatus = MediaPlaybackStatus.Stopped;
            }
        }
        public LandingPage()
        {
            this.InitializeComponent();
            this.Loaded    += LandingPage_Loaded;
            _timer          = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(5);
            _timer.Tick    += _timer_Tick;
            _media_control  = Windows.Media.SystemMediaTransportControls.GetForCurrentView();
            if (ApplicationHostPage.Host != null)
            {
                ApplicationHostPage.Host.GeoLocationChanged += Host_GeoLocationChanged;
                ApplicationHostPage.Host.AttendaceChanged   += Host_AttendaceChanged;
            }

            //set the application titlebar look
            var current_view   = ApplicationView.GetForCurrentView();
            var titlebar_color = Color.FromArgb(0xFF, 0x6A, 0x6A, 0x6A);

            current_view.TitleBar.BackgroundColor               = titlebar_color; //Colors.DarkGray;
            current_view.TitleBar.InactiveBackgroundColor       = titlebar_color;
            current_view.TitleBar.ButtonBackgroundColor         = titlebar_color;
            current_view.TitleBar.ButtonInactiveBackgroundColor = titlebar_color;
        }
Exemplo n.º 56
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Disable app UI rotation
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;

            // Prevent screen timeout
            m_displayRequest.RequestActive();

            // Handle app going to and coming out of background
#if WINDOWS_PHONE_APP
            Application.Current.Resuming   += App_Resuming;
            Application.Current.Suspending += App_Suspending;
            var ignore = InitializeCaptureAsync();
#else
            m_mediaControls = SystemMediaTransportControls.GetForCurrentView();
            m_mediaControls.PropertyChanged += m_mediaControls_PropertyChanged;

            if (!IsInBackground())
            {
                var ignore = InitializeCaptureAsync();
            }
#endif
        }
Exemplo n.º 57
0
        void SystemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs e)
        {
            switch (e.Button)
            {
            case SystemMediaTransportControlsButton.Play:
                Play();
                DisplayStatus(GetTimeStampedMessage("Play Pressed"));
                break;

            case SystemMediaTransportControlsButton.Pause:
                Pause();
                DisplayStatus(GetTimeStampedMessage("Pause Pressed"));
                break;

            case SystemMediaTransportControlsButton.Stop:
                Stop();
                DisplayStatus(GetTimeStampedMessage("Stop Pressed"));
                break;

            default:
                break;
            }
        }
Exemplo n.º 58
0
        private async void SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs e)
        {
            switch (e.Property)
            {
            case SystemMediaTransportControlsProperty.SoundLevel:
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    if (sender.SoundLevel != Windows.Media.SoundLevel.Muted)
                    {
                        ScenarioInit();
                    }
                    else
                    {
                        ScenarioClose();
                    }
                });

                break;

            default:
                break;
            }
        }
Exemplo n.º 59
0
        private void OnSmtcButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
            case SystemMediaTransportControlsButton.Play:

                // When the background task has been suspended and the SMTC
                // starts it again asynchronously, some time is needed to let
                // the task startup process in Run() complete.

                // Wait for task to start.
                // Once started, this stays signaled until shutdown so it won't wait
                // again unless it needs to.
                bool result = backgroundTaskStarted.WaitOne(5000);
                if (!result)
                {
                    throw new Exception("Background Task didnt initialize in time");
                }

                StartPlayback();
                break;

            case SystemMediaTransportControlsButton.Pause:

                BackgroundMediaPlayer.Current.Pause();

                break;

            case SystemMediaTransportControlsButton.Next:
                SkipToNext();
                break;

            case SystemMediaTransportControlsButton.Previous:
                SkipToPrevious();
                break;
            }
        }
Exemplo n.º 60
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");

            // Initialize SystemMediaTransportControls (SMTC) for integration with
            // the Universal Volume Control (UVC).
            //
            // The UI for the UVC must update even when the foreground process has been terminated
            // and therefore the SMTC is configured and updated from the background task.
            smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
            smtc.ButtonPressed    += AudioControlButtonPressed;
            smtc.PropertyChanged  += AudioControlPropertyChanged;
            smtc.IsEnabled         = true;
            smtc.IsPauseEnabled    = true;
            smtc.IsPlayEnabled     = true;
            smtc.IsNextEnabled     = true;
            smtc.IsPreviousEnabled = true;

            // Add handlers for MediaPlayer
            BackgroundMediaPlayer.Current.CurrentStateChanged += MediaPlayerStateChanged;
            BackgroundMediaPlayer.Current.MediaEnded          += MediaPlayerMediaEnded;

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

            // Send information to foreground that background task has been started if app is active
            MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());

            _deferral = taskInstance.GetDeferral(); // This must be retrieved prior to subscribing to events below which use it

            // Mark the background task as started to unblock SMTC Play operation (see related WaitOne on this signal)
            _backgroundTaskStarted.Set();

            // Associate a cancellation and completed handlers with the background task.
            taskInstance.Task.Completed += TaskCompleted;
            taskInstance.Canceled       += new BackgroundTaskCanceledEventHandler(OnCanceled); // event may raise immediately before continung thread excecution so must be at the end
        }