Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }

}
like image 325
HelloCW Avatar asked Sep 30 '20 12:09

HelloCW


1 Answers

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()

like image 80
Ramy Ibrahim Avatar answered Oct 26 '22 07:10

Ramy Ibrahim