请各位帮忙看看,谢谢!
调用MediaRecorder的stop方法时报java.lang.IllegalStateException
环境:
android:12及以上
JDK:17
说明:
录音部分未出现异常,在mr.stop()处发生上述异常
代码如下:
btnRecord.setOnTouchListener { _, event ->
val mr = MediaRecorder(root.context)
when (event.action) {
MotionEvent.ACTION_DOWN -> {
val fp = "${appDataPath!!}/btnRecord"
if(!FileUtil.mkDirs(fp)){
throw RuntimeException("指定的路径不存在,且未创建成功!")
}
if (checkSelfPermission(root.context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED){
RecordUtil.startRecord("${fp}/file${System.currentTimeMillis()}.3gp", mr)
}
}
MotionEvent.ACTION_MOVE -> {
// 当滑动时的处理
}
MotionEvent.ACTION_UP -> {
// 当抬起时的处理
RecordUtil.stopRecord(mr)
}
}
true // 返回true表示这个事件被处理了,不再传递
}
class RecordUtil {
companion object {
/**
* 开始录音
*/
@JvmStatic
public fun startRecord(fp: String, mr: MediaRecorder) {
//设置录音参数
try {
mr.setAudioSource(MediaRecorder.AudioSource.MIC) //1步
mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) //2步
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) //3步
mr.setOutputFile(fp)
mr.setAudioEncodingBitRate(128000) // 音频比特率
mr.setAudioSamplingRate(44100) // 音频采样率
mr.prepare()
mr.start()
} catch (ex: IllegalStateException) {
ex.printStackTrace()
} catch (ex: IOException) {
ex.printStackTrace()
}
}
/**
* 停止录音
*/
@JvmStatic
public fun stopRecord(mr: MediaRecorder) {
try {
mr.stop()
mr.release()
} catch (ex: IllegalStateException) {
ex.printStackTrace()
}
}
}
}