D
D
Dmtm2019-12-10 11:20:55
Android
Dmtm, 2019-12-10 11:20:55

How to throw an exception when accessing an AudioRecord?

can't test on real device yet, emulators only, API 28.29, microphone permission not granted

var recorder: AudioRecord? = null
        try {
            val minBufferSize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)

            require(!(minBufferSize == AudioRecord.ERROR || minBufferSize == AudioRecord.ERROR_BAD_VALUE))
            recorder = AudioRecord(
                    MediaRecorder.AudioSource.VOICE_COMMUNICATION,
                    8000,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    minBufferSize * 10)

            // Wait until audio record is initialized.
            var waitCycles = 20
            while (recorder.state != AudioRecord.STATE_INITIALIZED && waitCycles > 0) {
                Thread.sleep(250)
                waitCycles -= 1
            }
            if (recorder.state != AudioRecord.STATE_INITIALIZED) {
                throw Exception("Unable to initialize AudioRecord instance")
            }

            return recorder

I'm expecting a SecurityException to be thrown when creating an AudioRecord, but I'm getting just an uninitialized AudioRecord, how do I throw a SecurityException?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmtm, 2019-12-11
@Dmtm

this is a bug in the API, no one is going to rewrite the ancient code of the recorder

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question