Xamarin iOS Audio Player Notification

Step 1
 
Create a project in Xamarin iOS. New Project => Single View App. Give the Name
 
Step 2

Just Create a Media Player as you need. Add the following code in ViewDidLoad.
  1. public override void ViewDidLoad()  
  2.         {  
  3.             base.ViewDidLoad();  
  4.   
  5.             //To listen changes in lock screen  
  6.             UIApplication.SharedApplication.BeginReceivingRemoteControlEvents();  
  7.   
  8.             //creating an audio player with url  
  9.             mediaplayer = new AVPlayer(new Uri("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"));  
  10.                           
  11.             //make audio play when app goes background  
  12.             AVAudioSession.SharedInstance().SetActive(true);  
  13.             AVAudioSession.SharedInstance().SetCategory(AVAudioSessionCategory.Playback);  
  14.   
  15.             //Audio player Notification in lock screen  
  16.             MPNowPlayingInfo nowPlayingInfo;  
  17.             nowPlayingInfo = new MPNowPlayingInfo();  
  18.             nowPlayingInfo.Artist = "An OK Band";  
  19.             nowPlayingInfo.Title = "Our First Single!";            
  20.               
  21.             // Register for receiving controls from lock screen and controlscreen  
  22.             MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = nowPlayingInfo;  
  23.         }  
Step 3
 
Now we have to listen to changes in that media player notification as the user taps on next, play/pause, or previous.
  1. public override void RemoteControlReceived(UIEvent theEvent)  
  2.         {  
  3.             base.RemoteControlReceived(theEvent);  
  4.             if (theEvent.Subtype == UIEventSubtype.RemoteControlPreviousTrack)  
  5.             {  
  6.                  //Something you need to do.             
  7.             }  
  8.             else if (theEvent.Subtype == UIEventSubtype.RemoteControlNextTrack)  
  9.             {  
  10.                  //Something you need to do.             
  11.             }  
  12.             else  
  13.             {                 
  14.                 //Something you need to do.
  15.             }  
  16.         }  
Step 4
   
For each time the audio or video has changed, we have to update in "nowPlayingInfo
 
 
 
Step 5
 
That's all set. Now we are able to control our audio from the lock screen.
Ebook Download
View all
Learn
View all