How to encapsulate a custom MediaRecorder in Android Kotlin?

耗尽温柔 提交于 2019-12-10 12:09:16

问题


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?

来源:https://stackoverflow.com/questions/50072368/how-to-encapsulate-a-custom-mediarecorder-in-android-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!