gpt4 book ai didi

android - 如果我在暂停乐趣中启动 MediaRecorder.start() 并在 Android 中以正常乐趣启动 MediaRecorder.stop() 会导致错误吗?

转载 作者:行者123 更新时间:2023-12-03 13:27:45 28 4
gpt4 key购买 nike

录制音频是一个很长的操作,所以我启动mRecorder?.start()在服务内的协程中,您可以看到 RecordService.kt。
我调用 suspend fun startRecord(){...}AndroidViewModelviewModelScope.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()
}
}
记录服务.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()

关于android - 如果我在暂停乐趣中启动 MediaRecorder.start() 并在 Android 中以正常乐趣启动 MediaRecorder.stop() 会导致错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64137979/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com