Monday, June 15, 2015

// //

Sound recorder in android

What are we going to do? This time we will make a soundrecorder application.

1.
Sound recorder android
2.
Sound recorder android


 activity_main.xml

    

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

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

 MediaRecorder recorder;
 File soundfile = null;
 private static final String TAG = "record";
 private View startButtonrecord;
 private View stopButtonrecord;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  stopButtonrecord = findViewById(R.id.start);
  startButtonrecord = findViewById(R.id.stop);
 }

 public void startRecording(View view) throws IOException {

  stopButtonrecord.setEnabled(false);
  startButtonrecord.setEnabled(true);

  File sampleDir = Environment.getExternalStorageDirectory();
  try {
   soundfile = File.createTempFile("sound", ".3gp", sampleDir);
  } catch (IOException e) {
   Log.e(TAG, "sdcard access error");
   return;
  }
  recorder = new MediaRecorder();
  recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  recorder.setOutputFile(soundfile.getAbsolutePath());
  recorder.prepare();
  recorder.start();
 
 
 }

 public void stopRecording(View view) {
  stopButtonrecord.setEnabled(true);
  startButtonrecord.setEnabled(false);
  recorder.stop();
  recorder.release();
  recordingmedia();
 }

 protected void recordingmedia() {
  ContentValues values = new ContentValues(4);
  long current = System.currentTimeMillis();
  values.put(MediaStore.Audio.Media.TITLE, "audio" + soundfile.getName());
  values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
  values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
  values.put(MediaStore.Audio.Media.DATA, soundfile.getAbsolutePath());
  ContentResolver contentResolver = getContentResolver();

  Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  Uri newUri = contentResolver.insert(base, values);

  sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
  Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
 }
}

Don't forget to add this in the manifest:

    

You may also like:Save an audio file into a specific folder in android