2015-07-01 61 views
0

我已經通過msdn網站,stackoverflow等搜索了很多,但我無法在背景中播放一首歌曲。它停止時,改變框架,或退出應用程序返回到開始,它也隨機啓動時,它是在鎖屏或在其他地方..你能解釋如何正確做這個代碼請?對不起,代碼不好,但我已經在幾天前開始了。如何在Windows Phone 8.1中使用xaml和c#播放背景音樂?

這或多或少是我在微軟網站上發現的。還有沒有系統不會顯示任何控制

public sealed partial class listView : Page 
{ 
    SystemMediaTransportControls Player = SystemMediaTransportControls.GetForCurrentView(); 


    SystemMediaTransportControls systemControls; 
    MediaElement musicPlayer = new MediaElement(); 


    public listView() 
    { 

     this.InitializeComponent(); 
     makeSongList(); 

     // Per usare il tasto back 
     HardwareButtons.BackPressed += HardwareButtons_BackPressed; 

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

     // Register to handle the following system transpot control buttons. 
     systemControls.IsEnabled = true; 
     systemControls.IsPlayEnabled = true; 
     systemControls.IsPauseEnabled = true; 
     systemControls.IsNextEnabled = true; 
     systemControls.IsPreviousEnabled = true; 

     musicPlayer.AudioCategory = AudioCategory.BackgroundCapableMedia; 




    } 


    void MusicPlayer_CurrentStateChanged(object sender, RoutedEventArgs e) 
    { 
     // gestisce l'evento CurrentStateChanged di MediaElement e 
     // aggiorna la proprietà PlaybackStatus di SystemMediaTransportControls. 

     switch (musicPlayer.CurrentState) 
     { 
      case MediaElementState.Playing: 
       systemControls.PlaybackStatus = MediaPlaybackStatus.Playing; 
       break; 
      case MediaElementState.Paused: 
       systemControls.PlaybackStatus = MediaPlaybackStatus.Paused; 
       break; 
      case MediaElementState.Stopped: 
       systemControls.PlaybackStatus = MediaPlaybackStatus.Stopped; 
       break; 
      case MediaElementState.Closed: 
       systemControls.PlaybackStatus = MediaPlaybackStatus.Closed; 
       break; 
      default: 
       break; 
     } 
    } 

    async private void UpdateSongInfo() 
    { 
     // Get the updater. 
     SystemMediaTransportControlsDisplayUpdater updater = systemControls.DisplayUpdater; 

     // Get the music file and pass it to CopyFromFileAsync to extract the metadata 
     // and thumbnail. StorageFile is defined in Windows.Storage 
     StorageFile musicFile = 
      await StorageFile.GetFileFromApplicationUriAsync(new Uri(currentPath)); 

     await updater.CopyFromFileAsync(MediaPlaybackType.Music, musicFile); 

     // Update the system media transport controls 
     updater.Update(); 
    } 

    void MusicPlayer_MediaOpened(object sender, RoutedEventArgs e) 
    { 
     UpdateSongInfo(); 
    } 


    void SystemControls_ButtonPressed(SystemMediaTransportControls sender, 
             SystemMediaTransportControlsButtonPressedEventArgs args) 
    { 
     switch (args.Button) 
     { 
      case SystemMediaTransportControlsButton.Play: 
       PlayMedia(); 
       break; 
      case SystemMediaTransportControlsButton.Pause: 
       PauseMedia(); 
       break; 
      default: 
       break; 
     } 
    } 

    async void PlayMedia() 
    { 
     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,() => 
     { 
      musicPlayer.Play(); 
     }); 
    } 

    async void PauseMedia() 
    { 
     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,() => 
     { 
      musicPlayer.Pause(); 
     }); 
    } 

回答

1

解決這個問題!!!!

http://mark.mymonster.nl/2014/05

我被卡住,我讀的頁面千元,但該樣本是非常簡單明瞭!

主要問題是創建一個Windows運行時組件,並遵循其處理程序的backgroundMediaPlayer的運行性能的典型實現。

using System; 
using System.Diagnostics; 
using Windows.ApplicationModel.Background; 
using Windows.Foundation.Collections; 
using Windows.Media; 
using Windows.Media.Playback; 

namespace PLAYER 
{ 
    public sealed class BackgroundTask : IBackgroundTask 
    { 
     private string Artista { get; set; } 
     private string Titolo { get; set; } 
     private BackgroundTaskDeferral _deferral; 
     private SystemMediaTransportControls _systemMediaTransportControl; 

     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(); 
     } 

     private void MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e) 
     { 
      ValueSet valueSet = e.Data; 
      foreach (string key in valueSet.Keys) 
      { 
       switch (key) 
       { 

        case "Title": 
         Titolo = valueSet[key].ToString(); 


         break; 
        case "Artist": 
         Artista = valueSet[key].ToString(); 

         break; 
        case "Play": 
         Debug.WriteLine("Starting Playback"); 
         Play(valueSet[key].ToString()); 
         break; 



       } 

      } 
     } 

     private void Play(string toPlay) 
     { 
      MediaPlayer mediaPlayer = BackgroundMediaPlayer.Current; 
      mediaPlayer.AutoPlay = true; 
      mediaPlayer.SetUriSource(new Uri(toPlay)); 
      _systemMediaTransportControl.ButtonPressed += MediaTransportControlButtonPressed; 
      _systemMediaTransportControl.IsPauseEnabled = true; 
      _systemMediaTransportControl.IsPlayEnabled = true; 
      _systemMediaTransportControl.IsNextEnabled = true; 
      _systemMediaTransportControl.IsPreviousEnabled = true; 
      _systemMediaTransportControl.DisplayUpdater.Type = MediaPlaybackType.Music; 
      _systemMediaTransportControl.DisplayUpdater.MusicProperties.Artist = Artista; 
      _systemMediaTransportControl.DisplayUpdater.MusicProperties.Title = Titolo; 

      _systemMediaTransportControl.DisplayUpdater.Update(); 

     } 




     /// <summary> 
     ///  The MediaPlayer's state changes, update the Universal Volume Control to reflect the correct state. 
     /// </summary> 
     /// <param name="sender"></param> 
     /// <param name="args"></param> 
     private void BackgroundMediaPlayerCurrentStateChanged(MediaPlayer sender, object args) 
     { 
      if (sender.CurrentState == MediaPlayerState.Playing) 
      { 
       _systemMediaTransportControl.PlaybackStatus = MediaPlaybackStatus.Playing; 
      } 
      else if (sender.CurrentState == MediaPlayerState.Paused) 
      { 
       _systemMediaTransportControl.PlaybackStatus = MediaPlaybackStatus.Paused; 
      } 
     } 

     /// <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; 
      } 
     } 


     private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) 
     { 
      BackgroundMediaPlayer.Shutdown(); 
      _deferral.Complete(); 
     } 

     private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) 
     { 
      // You get some time here to save your state before process and resources are reclaimed 
      BackgroundMediaPlayer.Shutdown(); 
      _deferral.Complete(); 
     } 
    } 
} 
+0

儘管這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 –

+0

謝謝。更正:) – BADWOLF

+0

@BADWOLF,但我怎麼能使用它,我不知道如何讓taskInstance運行它 –

1

您使用SystemMediaTransportControls,所以它應該是Windows Phone的8.1在Windows運行的應用程序。

其實,你錯過了很多可以幫助你實現背景音頻的東西。例如:您沒有試圖獲得BackgroundTaskDeferral以保持後臺任務處於活動狀態,也沒有使用BackgroundMediaPlayer與全局媒體播放器進行通信以操縱音頻播放。

因此,我會建議先通過Overview: Background audio (Windows Phone Store apps)文章並檢查the offcial sample(您可以主要關注SampleBackgroundAudioTask項目中的MyBackgroundAudioTask.cs)實現。

相關問題