Android:强制音频路由

我想在Android应用中更改声音设备输出.我想在耳机插入时使用手机的扬声器.

我试过使用AudioManager中的setSpeakerphoneOn classaudioManager.setSpeakerphoneOn(true); with audioManager.setMode(AudioManager.MODE_IN_CALL);但我不想设置MODE_IN_CALL!我想留在MODE_NORMAL.

我搜索了AudioSystem类,我找到了一个应用程序“SoundAbout”,它就是这样做的.您可以为媒体音频选择扬声器,模式保持在NORMAL状态.

所以我在AudioSystem中尝试了setDeviceConnectionState来将DEVICE_OUT_WIRED_HEADPHONE设置为0但它不起作用.当我检查DEVICE_OUT_WIRED_HEADPHONE的状态时,它总是设置为1(AVAILABLE),我无法通过扬声器播放声音.

如何在不进入MODE_IN_CALL的情况下将DEVICE_OUT_WIRED_HEADPHONE设置为0或通过扬声器播放声音?

谢谢,抱歉我的英文不好!

我试试这个,它适用于我的情况:

class AudioSystem {

private static final int REFLECTION_ERROR = -999;

private static final String DEVICE_OUT_SPEAKER          = "DEVICE_OUT_SPEAKER";
private static final String DEVICE_OUT_EARPIECE         = "DEVICE_OUT_EARPIECE";
private static final String DEVICE_OUT_WIRED_HEADPHONE  = "DEVICE_OUT_WIRED_HEADPHONE";


Class<?> mAudioSystem;

protected AudioSystem() {

    try {
        mAudioSystem = Class.forName("android.media.AudioSystem");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

private int getConstantValue(String s) {

    try {
        return ((Integer)mAudioSystem.getDeclaredField(s).get(int.class)).intValue();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return REFLECTION_ERROR;

}


private int setDeviceConnectionState(int i, int j, String s) {

    try {
        return (Integer) mAudioSystem.getMethod("setDeviceConnectionState", int.class, int.class, String.class).invoke(mAudioSystem, i, j, s);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return REFLECTION_ERROR;
}

private int setDeviceConnectionState(String deviceName, Boolean state) {
    return setDeviceConnectionState(getConstantValue(deviceName), (state ? 1 : 0), "");
}

private void forceWiredHeadphonesMedia() {
    setDeviceConnectionState(DEVICE_OUT_WIRED_HEADPHONE, true);
    setDeviceConnectionState(DEVICE_OUT_SPEAKER, false);
}


private void forceSpeakerMedia() {
    setDeviceConnectionState(DEVICE_OUT_SPEAKER, true);
    setDeviceConnectionState(DEVICE_OUT_EARPIECE, true);
    setDeviceConnectionState(DEVICE_OUT_WIRED_HEADPHONE, false);
    setDeviceConnectionState(DEVICE_OUT_SPEAKER, true);
}

public void setSpeakerOn(Boolean state) {
    if (state) {
        forceSpeakerMedia();
    } else {
        forceWiredHeadphonesMedia();
    }
}

}

我使用setSpeakerOn(true)来禁用有线耳机.

限制:即使耳机已插入,AudioManager.isWiredHeadsetOn()也会返回false.

https://stackoverflow.com/questions/29969030/android-force-audio-routing

转载注明原文:Android:强制音频路由