I want to access rear and front speakers of android phones, programmatically.
How to access rear and front speaker of Android phones?
2.9k Views Asked by Talha Hafeez AtThere are 2 best solutions below

You can acquire either a rear speaker or a front earpiece at time.
If no accessory connected;
Use audioManager.setMode(AudioManager.MODE_IN_CALL);
& audioManager.setSpeakerphoneOn(false);
to use front speaker/earpiece. But this would play audio in earpiece not on speaker. To use rear speaker, useaudioManager.setMode(AudioManager.MODE_NORMAL);
& audioManager.setSpeakerphoneOn(true);
If accessory connected;
Use audioManager.setMode(AudioManager.MODE_IN_CALL);
& audioManager.setSpeakerphoneOn(false);
to use front speaker/earpiece. But this would play audio in earpiece not on speaker. To use rear speaker, useaudioManager.setMode(AudioManager.MODE_IN_CALL);
& audioManager.setSpeakerphoneOn(true);
Note: Make sure audioManager.setWiredHeadsetOn(boolean on)
and audioManager.setBluetoothScoOn(boolean on)
set to false.