Question

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());
    }
    
Was it helpful?

Solution

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();

OTHER TIPS

There is also important to add permission usage to manifest:

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top