Android: detect if sound from STREAM_VOICE_CALL is playing

658 views Asked by At

I'm looking for a way to check if other applications are using the STREAM_VOICE_CALL (for example during a phone call or while listening a whatsapp voice note bringing the phone to the ear) (but in general we should find a way to choose any stream to monitor). I need this for using in Tasker, but that should be irrelevant (but should help other people with the same problem finding this).

Basically this was just perfect:

AudioSystem.isStreamActive(int stream, int inPastMs)

which could be used with any audio stream... in my case

AudioSystem.isStreamActive(STREAM_VOICE_CALL, 0)

Too bad AudioSystem is now replaced with AudioManager class :( (info about AudioSystem in this other thread Android: Is there a way to detect if a sound from SoundPool is still playing )

Now we have AudioManager.isMusicActive which I have tried and it works flawlessly, but of course it refers to STREAM_MUSIC.

Any suggestion? Thanks

1

There are 1 answers

0
Nikola Despotoski On

AudioSystem is hidden API. You might need to use reflection to access it. Create extension for AudioManager and the use it as:

audioManager.isStreamActive(AudioManager.STREAM_SYSTEM)

Implementation:

private val AUDIO_SYSTEM_IS_STREAM_ACTIVE: Method by lazy { Class.forName("AudioSystem").getDeclaredMethod("isStreamActive",
    Integer::class.javaPrimitiveType, Integer::class.javaPrimitiveType).also { it.isAccessible = true }
}

fun AudioManager.isStreamActive(stream : Int) : Boolean {
    require(stream in -1..11){
        "Stream type must be between -1 (DEFAULT) and 11 (ASSISTANT)"
    }
    return when (stream) {
        AudioManager.STREAM_MUSIC -> {
            isMusicActive
        }
        AudioManager.STREAM_RING -> {
            ringerMode != AudioManager.RINGER_MODE_SILENT
                    && AUDIO_SYSTEM_IS_STREAM_ACTIVE.invoke(this, stream, 0) as Boolean
        }
        else -> {
            AUDIO_SYSTEM_IS_STREAM_ACTIVE.invoke(this, stream, 0) as Boolean
        }
    }
}