Xamarin.Tip – Playing Audio Through the Earpiece on Android

Xamarin provides plenty of documentation on how to play audio in Android:

However, this never touches on directing audio through the onboard earpiece for applications such as voicemail or other real-time uses. Here’s a quick and dirty service that can be used in Xamarin.Android to direct audio through either the speaker or the onboard earpiece:

AudioService.cs

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

        public void PlaySoundThroughEarPiece()
        {
            var mediaPlayer = new MediaPlayer();

            mediaPlayer.Reset();

            var audioManager = (AudioManager)Android.App.Application.Context.GetSystemService(Context.AudioService);
            mediaPlayer.SetAudioStreamType(Stream.VoiceCall);
            audioManager.Mode = Mode.InCall;
            audioManager.SpeakerphoneOn = false;
            mediaPlayer.SetDataSource(Android.App.Application.Context, Android.Net.Uri.Parse("android.resource://com.suavepirate.audiotest/raw/sample_sound"));
            mediaPlayer.Prepare();
            mediaPlayer.Start();
        }

        public void PlaySoundThroughSpeaker()
        {
            var mediaPlayer = MediaPlayer.Create(Android.App.Application.Context, Resource.Raw.sample_sound);


            var audioManager = (AudioManager)Android.App.Application.Context.GetSystemService(Context.AudioService);
            mediaPlayer.SetAudioStreamType(Stream.Music);
            audioManager.Mode = Mode.Normal;
            audioManager.SpeakerphoneOn = true;

            mediaPlayer.Start();
        }
    }

There are 2 important pieces required to stream it through the earpiece. Certain devices and Android versions only require 1 of the 2, but using both seems to be the best bet.

The first is to use the AudioManager service from the current Context and set SpeakerphoneOn to false as well as set the Mode to Mode.InCall. The second is to take the MediaPlayer object created and set the AudioStreamType to Stream.VoiceCall.

To go back to playing through the full speaker, revert the audio manager Mode to Normal, and set SpeakerphoneOn back to true. Be sure to also set the MediaPlayer.SetAudioStreamType with Stream.Music.

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.

One thought on “Xamarin.Tip – Playing Audio Through the Earpiece on Android”

Leave a comment