AudioRecord.getRoutedDevice() returns null on most of the Android device

766 views Asked by At

I'm trying to get current route for my input audio by calling AudioRecord.getRoutedDevice(); during recording, but on most Android API23+ devices it returns null (out of 300k various Android devices, only 10% return meaningful info). Even on the same device model (Samsung Galaxy S5, 6.0.1), 70% of devices return null, and 30% return correct info.

I tried to debug this using reflection, and replicated some of the SDK code to step through it - and I can see that inside of AudioRecord.getRoutedDevice(); I do get reasonable response both from native_getRoutedDeviceId() and getAudioManager().getDevices(), but then ids don't match:

@TargetApi(23)
private AudioDeviceInfo getRoutedDevice() {
    Object r = (Object)(0);
    try {
        Method method = _record.getClass().getDeclaredMethod("native_getRoutedDeviceId");
        method.setAccessible(true);
        r = method.invoke(_record);
    } catch (Exception e) {
        e.printStackTrace();
    }

    int deviceId = (int)r; //native_getRoutedDeviceId();
    if (deviceId == 0)
        return null;

    AudioDeviceInfo[] devices =
            getAudioManager().getDevices(AudioManager.GET_DEVICES_INPUTS);

    for (int i = 0; i < devices.length; i++)
        if (devices[i].getId() == deviceId)
            return devices[i];
    return null;
}

What could I be possibly doing wrong, and is there any other API that I could be using?

Old API like AudioManager.isWiredHeadsetOn() for example doesn't guarantee that audio IO is going through the headset at the moment.

1

There are 1 answers

3
MaxF On

From the docs

Note: The query is only valid if the AudioRecord is currently recording. If it is not, getRoutedDevice() will return null.