0

I am making an android app for testing phones and I need to be able to play a tone via the earphone speaker while headphones are plugged in. I am able to get the tone to play via the ear speaker when the headphones are not plugged in, but not when they are plugged in. Is there anyway to get my tone to play via the ear speaker when the headphones are plugged in? I will include the code that works without the headphones in.

    mp = MediaPlayer.create(getApplicationContext(), R.raw.tone_1ghz_5sec);
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    //set to false for through headphones
    audioManager.setSpeakerphoneOn(false);
    mp.start();

In other activities, I used the audio system class to force the speakers, is this the key here?

Toby
  • 141
  • 3
  • 12
  • 1
    Possible duplicate of [How to route default audio to ear piece when headphones are connected?](http://stackoverflow.com/questions/38461743/how-to-route-default-audio-to-ear-piece-when-headphones-are-connected) – tar Nov 29 '16 at 13:36
  • Thank you for directing me to that post. It helped me to solve my problem. – Toby Nov 29 '16 at 19:03

1 Answers1

1

I was able to get it to work. You can get it to go through the ear speaker, or call speaker, whatever you want to call it by the above code. If you then want to get it to still play via the call speaker, even though headphones are plugged in, you can do it just like this:

   AudioManager manager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    Class<?> cl = null;
    try {
        cl = Class.forName("android.media.AudioManager");
        setDeviceConnectionState = cl.getMethod("setWiredDeviceConnectionState", new Class[] {
                Integer.TYPE, Integer.TYPE, String.class });
        //4 is for the headset with microphone 8 is for headset without microphone
        //0 is for off and 1 is for on
        setDeviceConnectionState.invoke(manager, new Object[] { 4 , 0, "device" });
        setDeviceConnectionState.invoke(manager, new Object[] { 8 , 0, "device" });
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
Toby
  • 141
  • 3
  • 12
  • `setDeviceConnectionState` doesn't seem to work on Android 10 and above, the following error is logged: `AudioSystem-JNI: Command failed for android_media_AudioSystem_setDeviceConnectionState` . Any alternative working on recent SDK versions ? – sdabet Feb 18 '21 at 11:24