Recording audio is a long time operation, so I launch mRecorder?.start()
in a coroutine within a service, you can see RecordService.kt.
I invoke suspend fun startRecord(){...}
in AndroidViewModel
with viewModelScope.launch { }
to start record audio.
I only invoke a normal fun stopRecord(){...}
in AndroidViewModel
to stop record audio, you can see HomeViewModel.kt, will it cause error with the object var mRecorder: MediaRecorder?
?
HomeViewModel.kt
class HomeViewModel(val mApplication: Application, private val mDBVoiceRepository: DBVoiceRepository) : AndroidViewModel(mApplication) {
private var mService: RecordService? = null
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, iBinder: IBinder) {
val binder = iBinder as RecordService.MyBinder
mService = binder.service
}
...
}
fun bindService() {
Intent(mApplication , RecordService::class.java).also { intent ->
mApplication.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
}
fun unbindService() {
Intent(mApplication, RecordService::class.java).also { intent ->
mApplication.unbindService(serviceConnection)
}
}
fun startRecord(){
viewModelScope.launch {
mService?.startRecord()
}
}
fun stopRecord(){
mService?.stopRecord()
}
}
RecordService.kt
class RecordService : Service() {
private var mRecorder: MediaRecorder? = null
suspend fun startRecord(){
mRecorder = MediaRecorder()
withContext(Dispatchers.IO) {
mRecorder?.setOutputFile(filename);
mRecorder?.setMaxDuration(1000*60*20); //20 Mins
mRecorder?.setAudioChannels(1);
mRecorder?.setAudioSamplingRate(44100);
mRecorder?.setAudioEncodingBitRate(192000);
mRecorder?.prepare()
mRecorder?.start()
}
}
fun stopRecord(){
mRecorder?.stop()
mRecorder=null
}
}
No, it doesn't cause error but if you face runtime error while calling this method it may be caused by the recorder didn't receive any valid sound or video to record. Check below documentation link for more information.
https://developer.android.com/reference/android/media/MediaRecorder#stop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With