askIT

Record audio

Create new project

Create a new Android project with Android Studio.
I called my project "AudioRecord".
I used "nettport.com" as company domain and you can use your own domain.

01_new_project.jpg

I use API 21 (Android 5.0) as target.

02_api.jpg

I select a "Empty Activity".

03_activity.jpg

Click next on customize activity.

04_customize_activity.jpg

Android Manifest Permission

Go to "AndroidMainifest.xml" and add permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.STORAGE" />

Design

Add the microphone icon into "app -> res -> drawable".
My full path to this folder is
"C:\Users\bruker\AndroidStudioProjects\AudioRecord\app\src\main\pixel.pngres\drawable"

microphone_grey.png microphone_red.png

This icon will be used as image for a toggle button in "activity_main.xml". Add a Toggle Button to your design.

05_imagebutton.jpg

Give the button the ID "toggleButtonRecord".

05_imagebuttonrecord.jpg

Drawable Resource File

Create a new drawable resoruce file by right clicking on the value folder.
Give it the name "toggle_button_selector.xml"

06_layout_resource_file.jpg

toggle_button_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/microphone_grey"
android:state_pressed="true" />
<item android:drawable="@drawable/microphone_red"
android:state_checked="true" />
<item android:drawable="@drawable/microphone_grey"
android:state_checked="false" />
</selector>

Go to activity_main.xml and apply the toggle button selector background to the ToggleButton.

activity_main.xml

<ToggleButton
android:text="ToggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/toggleButtonRecord"
android:background="@drawable/toggle_button_selector" />

New java class

Create a new java class with the name "AudioRecorder".

07_new_java_class.jpg

package com.nettport.audiorecord;

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;
import android.os.Environment;

/**
* @author Ben McCann
*/

public class AudioRecorder {

        final MediaRecorder recorder = new MediaRecorder();
        final String path;

        /**
        * Creates a new audio recording at the given path (relative to root of SD card).
        */

        public AudioRecorder(String path) {
                this.path = sanitizePath(path);
        }

        private String sanitizePath(String path) {
                if (!path.startsWith("/")) {
                        path = "/" + path;
                }
                if (!path.contains(".")) {
                        path += ".3gp";
                }
                return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
        }

        /**
        * Starts a new recording.
        */

        public void start() throws IOException {
                String state = android.os.Environment.getExternalStorageState();
                if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
                        throw new IOException("SD Card is not mounted. It is " + state + ".");
                }

                // make sure the directory we plan to store the recording in exists
                File directory = new File(path).getParentFile();
                if (!directory.exists() && !directory.mkdirs()) {
                        throw new IOException("Path to file could not be created.");
                }

                recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                recorder.setOutputFile(path);
                recorder.prepare();
                recorder.start();
        }

        /**
        * Stops a recording that has been previously started.
        */

        public void stop() throws IOException {
                recorder.stop();
                recorder.release();
        }

}

MainActivity

The main activity code for registering if the record icon is pressed down or not is easy. First we need to fint the toggle button in the design, then create a listner for it. When the listner is checked then we run the method recordClicked. This method prints a toast message to the screen with the button status.

on.jpg on2.jpg

The recording will start when the button is pressed, and will continue until it is unpressed.

package com.nettport.audiorecord;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class MainActivity extends AppCompatActivity {

        String AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "AudioRecording.3gp";

        AudioRecorder myRecorder = new AudioRecorder(AudioSavePathInDevice);

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                /* Find image from design */
                ToggleButton imageButtonRecord = (ToggleButton)findViewById(R.id.toggleButtonRecord);
                boolean imageButtonRecordIsChecked = false;
                imageButtonRecord.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
                                recordClicked(isChecked) ;
                        }
                }) ;


                /* Storgate path */
                Toast.makeText(this, "Storage: " + AudioSavePathInDevice, Toast.LENGTH_SHORT).show();

        } //onCreate

        /* Record Clicked */
        void recordClicked(boolean isChecked){
                if(isChecked == true) {
                        Toast.makeText(this, "Start", Toast.LENGTH_SHORT).show();

                        try {
                                myRecorder.start();
                        } catch (IOException e) {
                                e.printStackTrace();
                                Toast.makeText(this, "Error: " + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                }
                else{
                        Toast.makeText(this, "Stop", Toast.LENGTH_SHORT).show();

                        try {
                                myRecorder.stop();
                        } catch (IOException e) {
                                e.printStackTrace();
                                Toast.makeText(this, "Error: " + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                }
        } // recordClicked


}

Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.