Xamarin.Tip – Playing Audio Through the Earpiece in iOS

There is plenty of documentation from Xamarin on how to play audio files in our Xamarin.iOS apps (or Xamarin.Forms apps):

But none of these talk about piping the audio to either the speaker or the earpiece (the onboard one used for phone calls). Handling this logic is useful for applications that have a “voicemail” sort of feature or a real-time communications app. Here’s a brief bit of code that can handle playing an audio file through the speaker or through the earpiece:

AudioService.cs

 public class AudioService : IAudioService
    {
        public AudioService()
        {
        }

        public void PlaySoundThroughEarPiece(string fileName)
        {
            var session = AVAudioSession.SharedInstance();
            session.SetCategory(AVAudioSessionCategory.PlayAndRecord);
            session.SetActive(true);
            NSError error;
            var player = new AVAudioPlayer(new NSUrl(fileName), "mp3", out error);
            player.Volume = 1.0f;
            player.Play();

        }

        public void PlaySoundThroughSpeaker(string fileName)
        {
            var session = AVAudioSession.SharedInstance();
            session.SetCategory(AVAudioSessionCategory.Playback);
            session.SetActive(true);
            NSError error;
            var player = new AVAudioPlayer(new NSUrl(fileName), "mp3", out error);
            player.Volume = 1.0f;
            player.Play();
            
        }
    }

The key is calling the SetCategory with the appropriate AVAudioSessionCategory and setting the session to active before playing the sound through the AVAudioPlayer.

and you can call it like so:

var audioService = new AudioService();
audioService.PlaySoundThroughEarPiece("sample_sound.mp3");
audioService.PlaySoundThroughSpeaker("sample_sound.mp3");

Check out an example of this on my GitHub here in Xamarin.Forms: https://github.com/SuavePirate/XamarinEarpieceAudioTest

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Leave a comment