Wednesday, 7 October 2020

Will it cause error if I launch MediaRecorder.start() in suspend fun and launch MediaRecorder.stop() in normal fun in Android?

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
    }

}


from Will it cause error if I launch MediaRecorder.start() in suspend fun and launch MediaRecorder.stop() in normal fun in Android?

No comments:

Post a Comment