robbpriestley
robbpriestley

Reputation: 3300

How to Control Background Audio Using Xamarin and iOS

I am new to Xamarin Forms and have a Xamarin Forms application which is playing background audio on iOS. In the simulator, I can go to the home screen and the audio is still audible.

I want to be able to use the transport controls on the lock screen like play/pause/fast-forward as well as seeing track title information.

I believe this article describes how to get an iOS app to interface with the required subsystem in order to achieve the goals I want, but I am unsure how to get it working in Xamarin. How can I do this?

Upvotes: 3

Views: 1378

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

Firstly ,Set it up in the Capabilities of the project to enable the background mode in info.plist. enter image description here

in AppDelegate.cs

//...
using AVFoundation;
//...

in the method FinishedLaunching

AVAudioSession session = AVAudioSession.SharedInstance();
session.SetCategory(AVAudioSessionCategory.Playback);
session.SetActive(true);

in the controller of you playmusic

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

Call the above method when you play a new song,and the following method will been called 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;
    }
}

Upvotes: 5

Related Questions