是否可以通过带耳机的耳机扬声器播放音调?

时间:2016-11-29 13:32:30

标签: android android-audiomanager

我正在制作用于测试手机的Android应用程序,我需要能够在插入耳机时通过耳机扬声器播放音调。当耳机没有时,我能够通过耳机播放音调插入,但插入时没有插入。当插入耳机时,无论如何都要通过耳机播放音调?我将包含没有耳机的代码。

    mp = MediaPlayer.create(getApplicationContext(), R.raw.tone_1ghz_5sec);
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    //set to false for through headphones
    audioManager.setSpeakerphoneOn(false);
    mp.start();

在其他活动中,我使用音频系统类强制扬声器,这是关键吗?

1 个答案:

答案 0 :(得分:1)

我能够让它发挥作用。无论您想通过上述代码调用它,您都可以通过耳机或呼叫扬声器。如果你想让它仍然通过通话扬声器播放,即使插入了耳机,你也可以这样做:

   AudioManager manager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    Class<?> cl = null;
    try {
        cl = Class.forName("android.media.AudioManager");
        setDeviceConnectionState = cl.getMethod("setWiredDeviceConnectionState", new Class[] {
                Integer.TYPE, Integer.TYPE, String.class });
        //4 is for the headset with microphone 8 is for headset without microphone
        //0 is for off and 1 is for on
        setDeviceConnectionState.invoke(manager, new Object[] { 4 , 0, "device" });
        setDeviceConnectionState.invoke(manager, new Object[] { 8 , 0, "device" });
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }