Reputation: 61
We've got an android application which records sound in a foreground service. Everything works as expected (AudioRecord initialization, audio recording, processing...) until restart of the device.
When the restart happens, our foreground service is succefully started, AudioRecord is successfully initialized, happily starts recording but always returns 0. No exception is thrown, no error code provided. We've tried both blocking and non-blocking way. This is the code starting recording:
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.RECORD_AUDIO
) != PackageManager.PERMISSION_GRANTED
) {
...
return
}
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);
audioRecord = AudioRecord(AUDIO_SOURCE, RECORDER_SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, BUFFER_SIZE_RECORDING);
if (audioRecord!!.state != AudioRecord.STATE_INITIALIZED) {
...
return
}
audioRecord?.startRecording()
isRecordingAudio = true
recordingThread = thread(true) {
try {
var position = 0
val fpStartUtc = Utilities.getActualUtcTime()
while (isRecordingAudio) {
val read = audioRecord?.read(wavBuffer, position, BUFFER_SIZE_RECORDING, AudioRecord.READ_NON_BLOCKING) ?: 0
//handle read errors
if (read < 0) {
val reason = when (read) {
AudioRecord.ERROR_INVALID_OPERATION -> "ERROR_INVALID_OPERATION"
AudioRecord.ERROR_BAD_VALUE -> "ERROR_BAD_VALUE"
AudioRecord.ERROR_DEAD_OBJECT -> "ERROR_DEAD_OBJECT"
AudioRecord.ERROR -> "ERROR"
else -> "UNKNOWN"
}
...
log_e("AudioRecord read error $reason")
break
}
position += read
if(!isRecordingAudio){
break
}
Thread.sleep(100)
}
Tested on sdk 33 and 34.
Upvotes: 1
Views: 44