如何使用 Xamarin 和 iOS 控制背景音频

rob*_*ley 3 ios xamarin.forms

我是 Xamarin Forms 新手,并且有一个在 iOS 上播放背景音频的 Xamarin Forms 应用程序。在模拟器中,我可以转到主屏幕,并且仍然可以听到音频。

我希望能够使用锁定屏幕上的传输控件,例如播放/暂停/快进以及查看曲目标题信息。

我相信本文描述了如何让 iOS 应用程序与所需的子系统交互以实现我想要的目标,但我不确定如何让它在 Xamarin 中工作。我怎样才能做到这一点?

Luc*_*ang 5

首先,在项目的Capability中进行设置,以启用后台模式info.plist在此输入图像描述

在 AppDelegate.cs 中

//...
using AVFoundation;
//...
Run Code Online (Sandbox Code Playgroud)

在方法中FinishedLaunching

AVAudioSession session = AVAudioSession.SharedInstance();
session.SetCategory(AVAudioSessionCategory.Playback);
session.SetActive(true);
Run Code Online (Sandbox Code Playgroud)

在你的控制器中播放音乐

public void SetLockInfo()
{

  NSMutableDictionary songInfo = new NSMutableDictionary();

  MPNowPlayingInfo playInfo = new MPNowPlayingInfo();

  //image
  MPMediaItemArtwork albumArt = new MPMediaItemArtwork(new UIImage("xxx.png"));
  playInfo.Artwork = albumArt;

  //title
  playInfo.Title = "your song name";

  //singer
  playInfo.Artist = "singer name";

  //rate
  playInfo.PlaybackRate = 1.0;

  //current time
  playInfo.ElapsedPlaybackTime = 0;

  //durtaion
  playInfo.PlaybackDuration = 2.35; // the durtaion of the song

  MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = playInfo;

  UIApplication.SharedApplication.BeginReceivingRemoteControlEvents();                          
}
Run Code Online (Sandbox Code Playgroud)

播放新歌时调用上面的方法,下面的方法会被调用auto

public void RemoteControlReceived(UIEvent controlEvent)
{
  switch(controlEvent.Subtype)
   {
     case UIEventSubtype.RemoteControlPlay:
          //play the music
          break;

     case UIEventSubtype.RemoteControlPause:
          //pause the music
          break;

     case UIEventSubtype.RemoteControlNextTrack:
          //play next one 
          break;

     case UIEventSubtype.RemoteControlPreviousTrack:
          //play last one 
          break;
     dafault:
          break;
    }
}
Run Code Online (Sandbox Code Playgroud)