0

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?

CEO tech4lifeapps
  • 885
  • 1
  • 12
  • 31
  • 1
    I'm not sure exactly what you mean. Could you please elaborate. thanks – Saskia Apr 28 '18 at 12:20
  • @Saskia I would like to have this code in a separate AudioRecorder.kt file/class. How can I do this? – CEO tech4lifeapps Apr 28 '18 at 13:41
  • 1
    I assume you use AndroidStudio to develop. Just create a new file and copy the code inside at.Since you're accessing the context you pass that as a class constructor to your new class. From your other questions I'm not sure you know how classes work. Have a look at https://kotlinlang.org/docs/reference/classes.html. You don't always need a companion object. – Saskia Apr 28 '18 at 15:00

0 Answers0