如何解决如果我在暂停状态下启动MediaRecorder.start并在Android中以正常状态启动MediaRecorder.stop,会引起错误吗?
录制音频是一项长时间的操作,因此我在服务中的协同程序中启动mRecorder?.start()
,您可以看到RecordService.kt。
我用suspend fun startRecord(){...}
调用AndroidViewModel
中的viewModelScope.launch { }
,开始录制音频。
我仅在fun stopRecord(){...}
中调用普通的AndroidViewModel
来停止录制音频,您可以看到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
}
}
解决方法
否,它不会引起错误,但是如果在调用此方法时遇到运行时错误,则可能是由于记录器未接收到任何有效的声音或视频来记录的。请查看下面的文档链接以获取更多信息。
https://developer.android.com/reference/android/media/MediaRecorder#stop()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。