【问题标题】:How to play background music in windows phone 8.1 with xaml and c#?如何使用 xaml 和 c# 在 windows phone 8.1 中播放背景音乐?
【发布时间】:2015-07-01 03:26:48
【问题描述】:

我通过 msdn 站点、stackoverflow 等进行了很多搜索。但我无法在后台播放歌曲。它在更改框架时停止,或者从应用程序退出返回开始,当它在锁屏或其他地方时它也会随机启动..你能解释一下这段代码的正确性吗?抱歉代码不好,但我几天前就开始了。

这或多或少是我在微软网站上找到的。也没有不显示任何控制的系统

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


    SystemMediaTransportControls systemControls;
    MediaElement musicPlayer = new MediaElement();


    public listView()
    {

        this.InitializeComponent();
        makeSongList();

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

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

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

        musicPlayer.AudioCategory = AudioCategory.BackgroundCapableMedia;




    }


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

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

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

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

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

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

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


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

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

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

【问题讨论】:

    标签: c# wpf xaml windows-phone-8.1


    【解决方案1】:

    您正在使用 SystemMediaTransportControls,因此它应该是适用于 windows phone 8.1 的 windows 运行时应用程序。

    实际上,您错过了许多可以帮助您实现背景音频的东西。例如:您没有尝试获取BackgroundTaskDeferral 来保持后台任务处于活动状态,并且您也没有使用BackgroundMediaPlayer 与全局媒体播放器进行通信以控制音频播放。

    所以我建议先看一下Overview: Background audio (Windows Phone Store apps)的文章,看看the offcial sample(你可以主要关注SampleBackgroundAudioTask项目中的MyBackgroundAudioTask.cs)是如何实现的。

    【讨论】:

      【解决方案2】:

      解决了这个问题!!!!

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

      我被困住了,我阅读了数千页,但那个示例真的很简单明了!

      主要问题是创建一个 windows 运行时组件,并遵循 backgroundMediaPlayer 及其处理程序的 Run istance 的典型实现。

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

      【讨论】:

      • @BADWOLF,但是我怎么用,我不知道怎么让taskInstance运行它
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      相关资源
      最近更新 更多