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