我想播放音频文件,而我有一个设备插入音频插孔(不一定只是耳机).
如果它有帮助我只对Android 4.3及以上版本感兴趣,我愿意在必要时根电话.
这是我到目前为止所尝试的:
>某种黑客但它不起作用.
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);
}
>在某个帖子中找到了这个,但它也无法正常工作:
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();
>使用MediaRouter类我尝试获取可用的路由.但是当插入音频插孔的东西时,只有可用的路线是“耳机”.
MediaRouter router = (MediaRouter) this.getSystemService(Context.MEDIA_ROUTER_SERVICE);
for (int i = 0; i < router.getRouteCount(); i++) {
Log.d("playSound", router.getRouteAt(i).toString());
}
解决方法:
我发现了如何做到这一点.请注意,MediaPlayer和AudioManger处于相同模式.我在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();