Hel*_*oCW 8 android android-service kotlin-coroutines
录制音频是一个长时间的操作,所以我mRecorder?.start()在一个服务内的一个协程中启动,你可以看到RecordService.kt。
我祈求suspend fun startRecord(){...}在AndroidViewModel与viewModelScope.launch { }开始录制音频。
我只调用一个正常的fun stopRecord(){...}inAndroidViewModel来停止录制音频,你可以看到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()
}
}
Run Code Online (Sandbox Code Playgroud)
记录服务.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
}
}
Run Code Online (Sandbox Code Playgroud)
不,它不会导致错误,但如果您在调用此方法时遇到运行时错误,可能是由于录音机没有收到任何有效的声音或视频来录制。检查下面的文档链接以获取更多信息。
https://developer.android.com/reference/android/media/MediaRecorder#stop()
| 归档时间: |
|
| 查看次数: |
172 次 |
| 最近记录: |