Lesson 29: Record audio using the MediaRecorder class in Kotlin

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

Contents

Another way to record audio on Android is to use the MediaRecorder class. This class gives us more freedom when it comes to building an application that requires audio recording.

Issue:

Create a project (Project032) Arrange three objects of the Button class with the labels “Record”, “Stop Recording” and “Play Recording”. Also, have a TextView to report the current status.

When the “Record” button is pressed, all sounds can be recorded until the “Stop Record” button is pressed. When the “Play Record” button is pressed, the previously generated audio file is output.

The visual interface to implement is as follows:

 

Lesson 29: Record audio using the MediaRecorder class in Kotlin - Lesson 29: Record audio using the MediaRecorder class in Kotlin - Lesson 29: Record audio using the MediaRecorder class in Kotlin -

We must also modify the file AndroidManifest.xml where we must indicate that our application will access the sound recorder and the SD card where the sound file will be stored.

This is done by selecting the file AndroidManifest.xml and typing the respective permissions:

 

Lesson 29: Record audio using the MediaRecorder class in Kotlin - Lesson 29: Record audio using the MediaRecorder class in Kotlin - Lesson 29: Record audio using the MediaRecorder class in Kotlin -

The source code in Kotlin is:

package com.coding180.project032


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Environment
import java.io.File
import android.widget.TextView
import java.io.IOException

class MainActivity : AppCompatActivity(), MediaPlayer.OnCompletionListener {
    lateinit var recorder: MediaRecorder
    lateinit var player: MediaPlayer
    lateinit var file: File
    lateinit var button1: Button
    lateinit var button2: Button
    lateinit var button3: Button
    lateinit var tv1: TextView
// coding180.com
    override fun onCreate (savedInstanceState: Bundle?) {
        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)

        tv1 = findViewById (R.id.tv1) as TextView
        button1 = findViewById (R.id.button1) as Button
        button2 = findViewById (R.id.button2) as Button
        button3 = findViewById (R.id.button3) as Button

        button1.setOnClickListener {
            recorder = MediaRecorder()
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
            val path = File (Environment.getExternalStorageDirectory().getPath())
            try {
                file = File.createTempFile ("temporary", ".3gp", path)
            } catch (e: IOException) {
            }

            recorder.setOutputFile(file.absolutePath)
            try {
                recorder.prepare ()
            } catch (e: IOException) {
            }

            recorder.start()
            tv1.text = "Recording"
            button1.setEnabled(false)
            button2.setEnabled(true)
        }

        button2.setOnClickListener {
            recorder.stop ()
            recorder.release ()
            player = MediaPlayer ()
            player.setOnCompletionListener (this)
            try {
                player.setDataSource(file.absolutePath)
            } catch (e: IOException) {
            }

            try {
                player.prepare ()
            } catch (e: IOException) {
            }

            button1.setEnabled (true)
            button2.setEnabled (false)
            button3.setEnabled (true)
            tv1.text = "Ready to play"
        }

        button3.setOnClickListener {
            player.start();
            button1.setEnabled (false);
            button2.setEnabled (false);
            button3.setEnabled (false);
            tv1.setText ("Playing");
        }
    }

    override fun onCompletion (mp: MediaPlayer) {
        button1.setEnabled (true)
        button2.setEnabled (true)
        button3.setEnabled (true)
        tv1.setText ("Ready")
    }
}

We declare an object of the MediaRecorder class to record audio:

    Lateinit var recorder: MediaRecorder

We declare an object of the MediaPlayer class to play the generated sound file:

    Lateinit var player: MediaPlayer

We declare an object of class File that refers to the file that will be created:

    Lateinit var archive: File

We declare the variables that will refer to the three buttons and the TextView:

    Lateinit var button1: Button
    Lateinit var button2: Button
    Lateinit var button3: Button
    Lateinit var tv1: TextView

In the onCreate method we obtain the reference of the four objects created in the XML file:

        Tv1 = findViewById (R.id.tv1) as TextView
        Button1 = findViewById (R.id.button1) as Button
        Button2 = findViewById (R.id.button2) as Button
        Button3 = findViewById (R.id.button3) as Button

The most important method of this concept is to record:

        button1.setOnClickListener {
            Recorder = MediaRecorder ()
            Recorder.setAudioSource (MediaRecorder.AudioSource.MIC)
            Recorder.setOutputFormat (MediaRecorder.OutputFormat.THREE_GPP)
            Recorder.setAudioEncoder (MediaRecorder.AudioEncoder.AMR_NB)
            Val path = File (Environment.getExternalStorageDirectory ()
                    .getPath ())
            Try {
                File = File.createTempFile ("temporary", ".3gp", path)
            } Catch (e: IOException) {
            }

            Recorder.setOutputFile (.absolutePath file)
            Try {
                Recorder.prepare ()
            } Catch (e: IOException) {
            }

            Recorder.start ()
            Tv1.text = "Recording"
            Button1.setEnabled (false)
            Button2.setEnabled (true)
        }

We create an object of class MediaRecorder:

            Recorder = MediaRecorder ()

Next we define the microphone as an audio source:

            Recorder.setAudioSource (MediaRecorder.AudioSource.MIC)

Then we call the setOutputFormat method specifying that the file will be stored with the 3GPP specification and extension .3gp

            Recorder.setOutputFormat (MediaRecorder.OutputFormat.THREE_GPP)

Specify the codec to use by calling the setAudioEncoder method:

            Recorder.setAudioEncoder (MediaRecorder.AudioEncoder.AMR_NB)

Obtain the path of the SD card and create a temporary file with extension 3gp:

            Val path = File (Environment.getExternalStorageDirectory ()
                    .getPath ())
            Try {
                File = File.createTempFile ("temporary", ".3gp", path)
            } Catch (e: IOException) {
            }

With the method setOutputFile of the class MediaRecorder we indicate the file where the recording should be stored:

            Recorder.setOutputFile (.absolutePath file)

We call the prepare method and finally the start method to start the recording:

            Recorder.setOutputFile (.absolutePath file)
            Try {
                Recorder.prepare ()
            } Catch (e: IOException) {
            }

The second button’s lambda function stops recording:

        Button2.setOnClickListener {
            Recorder.stop ()
            Recorder.release ()
            Player = MediaPlayer ()
            Player.setOnCompletionListener (this)
            Try {
                Player.setDataSource (.absolutePath file)
            } Catch (e: IOException) {
            }

            Try {
                Player.prepare ()
            } Catch (e: IOException) {
            }

            Button1.setEnabled (true)
            Button2.setEnabled (false)
            Button3.setEnabled (true)
            Tv1.text = "Ready to play"
        }

We first call the stop method of the MediaRecorder class and release the resources consumed by calling release:

            Recorder.stop ()
            Recorder.release ()

We create an object of the class MediaPlayer to be able to reproduce the audio file that we just recorded. We indicate by means of the setOnCompletionListener method the reference of the class that will be informed when the audio ends:

            Player = MediaPlayer ()
            Player.setOnCompletionListener (this)

We refer to the file to be played:

            Try {
                Player.setDataSource (.absolutePath file)
            } Catch (e: IOException) {
            }

Finally, we call the prepare method of the MediaPlayer class:

            Try {
                Player.prepare ()
            } Catch (e: IOException) {
            }

The lambda function to play simply calls the start method of the MediaPlayer class to start playback of the previously recorded file:

        Button3.setOnClickListener {
            Player.start ();
            Button1.setEnabled (false);
            Button2.setEnabled (false);
            Button3.setEnabled (false);
            Tv1.setText ("Playing");
        }

The onCompletion method is executed when the audio file is playing:

    Override fun onCompletion (mp: MediaPlayer) {
        Button1.setEnabled (true)
        Button2.setEnabled (true)
        Button3.setEnabled (true)
        Tv1.setText ("Ready")
    }

…….

About The Author

Related posts

Leave a Reply