Voice recording with Mediarecorder Android Studio

Asked

Viewed 1,743 times

0

I’m working on a project with voice recording, I’m halfway there, I’m already with the recorder working and saving the recording according to the code below, but I’m having some problems: 1º I can’t create a folder to save the audios to then display, All the audios are in the root directory, 2nd I cannot list the audios in the listview, 3rd I have no idea how to delete the audios after created and displayed in Listview. follows the code of the writer . java and XML. OBS: I will not put the code of the listview display because it has nothing implemented.

import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;

import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class Gravador extends AppCompatActivity {

Button buttonStart, buttonStop, buttonPlayLastRecordAudio, buttonStopPlayingRecording ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;

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

    buttonStart = (Button) findViewById(R.id.button);
    buttonStop = (Button) findViewById(R.id.button2);
    buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
    buttonStopPlayingRecording = (Button)findViewById(R.id.button4);

    buttonStop.setEnabled(false);
    buttonPlayLastRecordAudio.setEnabled(false);
    buttonStopPlayingRecording.setEnabled(false);

    random = new Random();

    buttonStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(checkPermission()) {

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

                MediaRecorderReady();

                try {
                    mediaRecorder.prepare();
                    mediaRecorder.start();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                buttonStart.setEnabled(false);
                buttonStop.setEnabled(true);

                Toast.makeText(Gravador.this, "Recording started", Toast.LENGTH_LONG).show();
            }
            else {

                requestPermission();

            }

        }
    });

    buttonStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            mediaRecorder.stop();

            buttonStop.setEnabled(false);
            buttonPlayLastRecordAudio.setEnabled(true);
            buttonStart.setEnabled(true);
            buttonStopPlayingRecording.setEnabled(false);

            Toast.makeText(Gravador.this, "Recording Completed", Toast.LENGTH_LONG).show();

        }
    });

    buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) throws IllegalArgumentException, SecurityException, IllegalStateException {

            buttonStop.setEnabled(false);
            buttonStart.setEnabled(false);
            buttonStopPlayingRecording.setEnabled(true);

            mediaPlayer = new MediaPlayer();

            try {
                mediaPlayer.setDataSource(AudioSavePathInDevice);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }

            mediaPlayer.start();

            Toast.makeText(Gravador.this, "Recording Playing", Toast.LENGTH_LONG).show();

        }
    });

    buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            buttonStop.setEnabled(false);
            buttonStart.setEnabled(true);
            buttonStopPlayingRecording.setEnabled(false);
            buttonPlayLastRecordAudio.setEnabled(true);

            if(mediaPlayer != null){

                mediaPlayer.stop();
                mediaPlayer.release();

                MediaRecorderReady();

            }

        }
    });
}

public void MediaRecorderReady(){

    mediaRecorder=new MediaRecorder();

    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

    mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);

    mediaRecorder.setOutputFile(AudioSavePathInDevice);

}

public String CreateRandomAudioFileName(int string){

    StringBuilder stringBuilder = new StringBuilder( string );

    int i = 0 ;
    while(i < string ) {

        stringBuilder.append(RandomAudioFileName.charAt(random.nextInt(RandomAudioFileName.length())));

        i++ ;
    }
    return stringBuilder.toString();

}

private void requestPermission() {

    ActivityCompat.requestPermissions(Gravador.this, new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);

}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case RequestPermissionCode:
            if (grantResults.length > 0) {

                boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean RecordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                if (StoragePermission && RecordPermission) {

                    Toast.makeText(Gravador.this, "Permission Granted", Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(Gravador.this,"Permission Denied",Toast.LENGTH_LONG).show();

                }
            }

            break;
    }
}

public boolean checkPermission() {

    int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
    int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);

    return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}

}

XML of the Recorder

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/mic_pic"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Record"
    android:id="@+id/button"
    android:layout_below="@+id/imageView"
    android:layout_alignParentLeft="true"
    android:layout_marginTop="37dp"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="STOP"
    android:id="@+id/button2"
    android:layout_alignTop="@+id/button"
    android:layout_centerHorizontal="true"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Play"
    android:id="@+id/button3"
    android:layout_alignTop="@+id/button2"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="STOP PLAYING RECORDING "
    android:id="@+id/button4"
    android:layout_below="@+id/button2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"

        />
</RelativeLayout>

1 answer

0

Good Charlie has more than one doubt so I’ll try to help you in steps:

  1. Save audio to a specific folder:

According to this reply of the Gringo SO:

File f = new File(Environment.getExternalStorageDirectory() + "/suapasta");

if (f.isDirectory()) {
        //Seu codigo caso o "suapasta" seja um diretorio

} else {

        // cria um objeto File pro diretorio pai
        File wallpaperDirectory = new File("/sdcard/Wallpaper/");
        // cria a pasta caso seja necessario
        wallpaperDirectory.mkdirs();
       // cria o objeto File pro output
       File outputFile = new File(wallpaperDirectory, filename);
       // agora adiciona o OutputStream no seu arquivo
       FileOutputStream fos = new FileOutputStream(outputFile);

}

This code checks if the location where Voce wants to save is a folder (it won’t be the first time saving, or if it deletes the data from the device) and if so, Voce already saves direct as it would in the root folder, or it creates the folder for Voce and then you save the file (recommend an auxiliary way to save to avoid duplicate code)

  1. Show in listview

This seems more to be a question of not knowing how Listview works than having to do with audio, so I strongly recommend you take a look at the Listview documentation (unless it is a requirement to use Listview, I also strongly recommend, but strongly, taking a look at Recyclerview instead of Listview)

Follows the documentation:

Listview

How to Create Lists and Cards

But the basic idea on top of that is that Voce needs to create a layout for each item in its list, have a list of audio objects (or a container class with more information about the audio) that will be passed to Adapter, create an Adapter that relates your layout to each item in the list (look for Listview/Recyclerview Adapter that finds a lot in Google) and I believe that Voce also wants to relate each audio to an element in the list, This is easy to do on Adapter when Voce understands the concept.

  1. Deleting the audio files

Well, I didn’t quite understand this doubt, because if you delete them they won’t be able to use them in Listview to play, so if you can leave a comment explaining better what you meant by that I edit.

I’m sorry if I didn’t answer all the questions but it was a very long question, I hope I helped

  • Opa muito obrigado pela dica, I’m new in the area of Mobile development, questao de deletar seria depois de já estar listados os audios, IE, appearing all in the list, I want to delete certain audio I recorded that I no longer want to use or I don’t want it to appear on the list. Another question is how I could put a name before saving Audio?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.