I\'m recording the sound from device with AudioRecord and write it to .wav file and I need it to keep recording and writing in file even wh
You should start recording/initialize AudioRecord
in independent thread, and start this thread you need from foreground Service
. Also right before start of recording change thread priority like in example below:
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);
AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC,
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize);
record.startRecording();
The answer by @Raskilas works!
However, it doesn't include much of the actual code needed, so I've put together a Github Gist which demonstrates the approach: https://gist.github.com/Venryx/e1f772b4c05b2da08e118ccd5cc162ff
It's not a completely finished project (and has extra stuff that isn't needed), but it includes all the important bits, and I can confirm it's working on my device (Mi Mix 3, Android 9), even when its screen is turned off. (I press power and wait 30+ minutes, and it's still logging the microphone input. My previous attempts all stopped ~2 minutes in.)
Interestingly, I didn't even need to activate a wake-lock or wifi-lock; however, functions to do so are included in the Gist as well, in case you find it's needed for your device, and/or to prevent other functionality from being suspended.