I am new to Kotlin programming. I use the following code to record audio as part of my 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()
}
This works flawlessly. However, I would like to encapsulate this code in an AudioRecorder class
. How exactly would I do that?