安卓 - 当设备插入音频插孔时播放声音

4
我希望在设备插入音频插孔时(不仅限于耳机),可以播放音频文件,与Android 4.3及以上版本有关,如有必要,我愿意获取root权限。
以下是我目前尝试过的方法:
  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());
    }
    

它到底是怎么不工作的? - ozbek
这不是一种预期/正常的行为吗? - ozbek
你没有提到你在播放中使用哪种流类型。这非常重要。 - Michael
@Michael,我不确定你在说什么? - Koc
我尝试添加以下代码:MediaPlayer mp = MediaPlayer.create(this, R.raw.bad); mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 但是这个hack仍然无效(设备:Nexus 5) - Koc
显示剩余5条评论
2个回答

1

在清单文件中添加权限使用也很重要:

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

1
我发现如何实现这个。请注意,MediaPlayer和AudioManager处于相同的模式中。我在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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接