我正在使用 MediaRecorder 录制音频文件,我已经设置了必要的代码,代码工作正常,直到我在抛出异常后立即按下停止录制,导致应用程序崩溃,不知道到底是什么问题!我很高兴能得到你们的帮助,谢谢你们
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.sendIcon.setOnClickListener {
startRecording()
}
binding.recordingIcon.setOnClickListener {
stopRecording()
}
}
private fun startRecording() {
if (mediaRecorder == null){
mediaRecorder = MediaRecorder()
mediaRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
mediaRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
mediaRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
mediaRecorder!!.setAudioSamplingRate(16000)
mediaRecorder!!.setOutputFile(getOutputFilePath())
try {
mediaRecorder!!.prepare()
mediaRecorder!!.start()
} catch (e: Exception) {
Log.d("TAG","Recording Exception " + e.localizedMessage)
}
}
}
private fun stopRecording() {
if (mediaRecorder != null){
mediaRecorder?.stop()
mediaRecorder?.release()
}
}
private fun getOutputFilePath(): String {
val recordingID = "Recording_" + System.currentTimeMillis()
val directory = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
applicationContext.getExternalFilesDir(Environment.DIRECTORY_MUSIC)
} else {
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
}
return directory?.absolutePath + "/AudioRecording/" + recordingID + ".3gp"
}
它不起作用的原因是它在调用
prepare
/start
方法时抛出异常。特别是,该问题与打开输出文件有关 (open failed: ENOENT
)。
根据文档的建议,您可以通过以下方式提供存储输出文件的目录:
val fileName = "${externalCacheDir?.absolutePath}/audiorecordtest.3gp"
mediaRecorder!!.setOutputFile(fileName)
当然你要根据自己的需要调整这个建议。
希望这有帮助。