我是Kotlin编程的新手。我使用以下代码将音频录制为 AudioRecorderDialogFragment的一部分:
fun startVoiceRecorder(voiceFilename: String) {
if (mAudioRecorder == null) {
// We don't have an AudioRecorder, so we build one
mAudioRecorder = MediaRecorder()
mAudioRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC)
mAudioRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
mAudioRecorder?.setAudioEncoder(MediaRecorder.OutputFormat.MPEG_4)
val audioOutputFile = Environment.getExternalStorageDirectory().absolutePath + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + voiceFilename
mAudioRecorder?.setOutputFile(audioOutputFile)
}
// We do have an AudioRecorder
if (!isRecording!!) {
// We try to record
try {
mAudioRecorder?.prepare()
mAudioRecorder?.start()
isRecording = true
} catch (e: IllegalStateException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
} else { // We seem to be recording already
isRecording = false
if (null != mAudioRecorder) {
try {
mAudioRecorder?.stop()
} catch (ex: RuntimeException) {
// Ignore
}
}
mAudioRecorder?.reset()
mAudioRecorder?.release()
mAudioRecorder = null
}
}
fun stopVoiceRecorder() {
isRecording = false
if (null != mAudioRecorder) {
try {
mAudioRecorder?.stop()
} catch (ex: RuntimeException) {
// Ignore
}
}
mAudioRecorder?.reset()
mAudioRecorder?.release()
mAudioRecorder = null
Toast.makeText(context, "Audio recorded successfully", Toast.LENGTH_LONG).show()
}
这完美无瑕。但是,我想将此代码封装在AudioRecorder class
中。我到底该怎么做?