3

The following Code A is from the sample project.

It use the Code B to record voice and save as file.

Code B

setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)

You know the getExtensionText() will return two audio format, mp3 or m4a by user settings , there are different audio format.

I don't know why the author can use only Code B to generate two different audio format file.

Can MediaRecorder save voice as mp3 or m4a audio format file automatically based file name extension in Android Studio?

Code A

    // mp4 output format with aac encoding should produce good enough m4a files according to https://stackoverflow.com/a/33054794/1967672
    private fun startRecording() {
        val baseFolder = if (isQPlus()) {
            cacheDir
        } else {
            val defaultFolder = File(config.saveRecordingsFolder)
            if (!defaultFolder.exists()) {
                defaultFolder.mkdir()
            }

            defaultFolder.absolutePath
        }

        currFilePath = "$baseFolder/${getCurrentFormattedDateTime()}.${config.getExtensionText()}"
        recorder = MediaRecorder().apply {
            setAudioSource(MediaRecorder.AudioSource.CAMCORDER)
            setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
            setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
            setAudioEncodingBitRate(128000)
            setAudioSamplingRate(44100)

         ...

      }



  class Config(context: Context) : BaseConfig(context) {
    ...

   
    fun getExtensionText() = context.getString(when (extension) {
        EXTENSION_M4A -> R.string.m4a
        else -> R.string.mp3
    })
 }
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

2

Actually, they already defined the file extension in the SettingsActivity.kt but you can use the file name with the extension. Actually, In this code, you can use any extension of the supported media formats.

        mediaRecorder = MediaRecorder()
        output = Environment.getExternalStorageDirectory().absolutePath + "/recording.mp3"

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC)
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
        mediaRecorder.setOutputFile(output)

for the full code see this or here

I_Al-thamary
  • 3,385
  • 2
  • 24
  • 37
  • Thanks! Yes, they already defined the file extension mp3 or m4a, but can `setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) setAudioEncoder(MediaRecorder.AudioEncoder.AAC)` generate different audio format by file extension ? – HelloCW Apr 19 '21 at 02:39
  • I already updated the answer and I hope that answer your question. – I_Al-thamary Apr 19 '21 at 14:40