Android - play sound when device plugged in audio jack

2k views Asked by At

I want to play audio file while I have a device plugged in audio jack (not necessary just headphones).

If it helps I am only interested in Android version 4.3 and above and I am willing to root the phone if necessary.

Here is what I have tried so far:

  1. Some kind of hack but it is not working.

     try {
        Class audioSystemClass = Class.forName("android.media.AudioSystem");
        Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
        setForceUse.invoke(null, 1, 1);
    
        MediaPlayer mp = MediaPlayer.create(this, R.raw.bad);
        mp.start();
    
    } catch (ClassNotFoundException e) {
        Log.d("mediaException", "class", e);
    } catch (NoSuchMethodException e) {
        Log.d("mediaException", "method", e);
    } catch (IllegalAccessException e) {
        Log.d("mediaException", "access", e);
    } catch (InvocationTargetException e) {
        Log.d("mediaException", "invocation", e);
    }
    
  2. Found this here in some thread but it is also not working:

    AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    
    audioManager.setMode(AudioManager.MODE_NORMAL);
    audioManager.setSpeakerphoneOn(true);
    
    MediaPlayer mp = MediaPlayer.create(this, R.raw.bad);
    mp.start();
    
  3. Using MediaRouter class I tried to get available routes. But when something is plugged in audio jack only route available is "Headphones".

    MediaRouter router = (MediaRouter) this.getSystemService(Context.MEDIA_ROUTER_SERVICE);
    
    for (int i = 0; i < router.getRouteCount(); i++) {
        Log.d("playSound", router.getRouteAt(i).toString());
    }
    
2

There are 2 answers

0
Koc On BEST ANSWER

I found out how this can be done. Notice that MediaPlayer and AudioManger are in the same mode. I tried this on Nexus 5 (4.4.2)

        final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        audioManager.setSpeakerphoneOn(true);

        MediaPlayer mp = null;
        mp = MediaPlayer.create(this, R.raw.bad);
        mp.setAudioStreamType(AudioManager.MODE_IN_COMMUNICATION);
        mp.start();
0
Fedir Tsapana On

There is also important to add permission usage to manifest:

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />