如果我在 suspend fun 中启动 MediaRecorder.start() 并在 Android 中在 normal fun 中启动 MediaRecorder.stop() 是否会导致错误?

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

录音是一个很耗时的操作,所以我在服务中的协程中启动mRecorder?.start(),你可以看到RecordService.kt。

我在 AndroidViewModel 中用 viewModelScope.launch { } 调用 suspend fun startRecord(){...} 开始录制音频。

我只是在AndroidViewModel中调用了一个普通的fun stopRecord(){...}来停止录音,你可以看到HomeViewModel.kt,会不会导致对象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
    }

}

不,它不会导致错误,但如果您在调用此方法时遇到运行时错误,则可能是由于录音机没有收到任何有效的声音或视频来录制。查看以下文档 link 了解更多信息。

https://developer.android.com/reference/android/media/MediaRecorder#stop()