0

I am trying to record from the microphone and I built a code by trying some code snippets else where but nothing happens: Here is the code, can someone tell me how to get this working.I am new to android coding.

package com.example.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.AudioFormat;
import android.media.AudioRecord;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.util.Log;
import java.io.*;  
import android.os.Environment;

public class MainActivity extends Activity {
    public static final int SAMPLING_RATE = 44100;
    public static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
    public static final int CHANNEL_IN_CONFIG = AudioFormat.CHANNEL_IN_MONO;
    public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    public static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLING_RATE, CHANNEL_IN_CONFIG, AUDIO_FORMAT);
    public static final String AUDIO_RECORDING_FILE_NAME = "recording.raw";
    private static final String LOGTAG = "MyActivity";
    private volatile boolean mStop = true;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView text = new TextView(this);
        text.setText("Hello World, Ranjan");
        setContentView(text);
    }

    /*public void run() 
    {

        TextView text = new TextView(this);
        text.setText(" hello smart mute");

    }*/
    //@Override
    public void run() {
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
        Log.v(LOGTAG, "Starting recording…");

        byte audioData[] = new byte[BUFFER_SIZE];
        AudioRecord recorder = new AudioRecord(AUDIO_SOURCE,
                    SAMPLING_RATE, CHANNEL_IN_CONFIG,
                    AUDIO_FORMAT, BUFFER_SIZE);
        recorder.startRecording();

        String filePath = Environment.getExternalStorageDirectory().getPath()
                    + "/" + AUDIO_RECORDING_FILE_NAME;
        BufferedOutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(filePath));
        } catch (FileNotFoundException e) {
            Log.e(LOGTAG, "File not found for recording ", e);
        }

        while (!mStop) {
            int status = recorder.read(audioData, 0, audioData.length);

            if (status == AudioRecord.ERROR_INVALID_OPERATION ||
                status == AudioRecord.ERROR_BAD_VALUE) {
                Log.e(LOGTAG, "Error reading audio data!");
                return;
            }

            try {
                os.write(audioData, 0, audioData.length);
            } catch (IOException e) {
                Log.e(LOGTAG, "Error saving recording ", e);
                return;
            }
        }

        try {
            os.close();

            recorder.stop();
            recorder.release();

            Log.v(LOGTAG, "Recording done…");
            mStop = false;

        } catch (IOException e) {
            Log.e(LOGTAG, "Error when releasing", e);
        }
    }
}
comrade
  • 4,590
  • 5
  • 33
  • 48
  • "nothing happens" is generic. what is the issue that you are facing? Not able to save file ? Not able to read file? Or finding the saved file ? – Sreehari Jul 06 '16 at 06:59
  • No file gets created.I want to process the audio data coming from the mic in real time.Say after I get a 1000 samples of audio data from the mic ,I want to process it with my algo. Now I also want to get audio data from the second microphone that my phone has.How shall I do it? – Sriranjan Rasakatla Jul 06 '16 at 07:07
  • Also what I have seen is that the run function is overridden, in my case I commented off the override symbol just before run.I am new to java as as well. Should I create a runnable instance and then put run function in it? – Sriranjan Rasakatla Jul 06 '16 at 07:10

1 Answers1

0

Add these to your manifest file

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

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

Try the below code,it helps us to record,stop and play audio

public class MainActivity extends Activity {
Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  play=(Button)findViewById(R.id.button3);
  stop=(Button)findViewById(R.id.button2);
  record=(Button)findViewById(R.id.button);

  stop.setEnabled(false);
  play.setEnabled(false);
  outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;

  myAudioRecorder=new MediaRecorder();
  myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
  myAudioRecorder.setOutputFile(outputFile);

  record.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        try {
           myAudioRecorder.prepare();
           myAudioRecorder.start();
        }

        catch (IllegalStateException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

        catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

        record.setEnabled(false);
        stop.setEnabled(true);

        Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
     }
  });

  stop.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        myAudioRecorder.stop();
        myAudioRecorder.release();
        myAudioRecorder  = null;

        stop.setEnabled(false);
        play.setEnabled(true);

        Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
     }
  });

  play.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
        MediaPlayer m = new MediaPlayer();

        try {
           m.setDataSource(outputFile);
        }

        catch (IOException e) {
           e.printStackTrace();
        }

        try {
           m.prepare();
        }

        catch (IOException e) {
           e.printStackTrace();
        }

        m.start();
        Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
     }
  });
}
raasesh
  • 161
  • 11
  • I want to get raw data from both the mics on my phone.How shall I get data from my second mic.My phone has two mics. – Sriranjan Rasakatla Jul 06 '16 at 10:27
  • The second microphone is used for noise cancelling. The phone uses it to listen to the external environment (not including your voice), so that it can filter that out from the sounds it hears using the main microphone. – raasesh Jul 07 '16 at 09:52
  • [Microphone link....](http://stackoverflow.com/questions/15418267/how-to-access-the-second-mic-android-such-as-galaxy-3) visit the above link for more clarification. – raasesh Jul 07 '16 at 09:56
  • AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.CAMCORDER, SAMPLE_RATE, AudioFormat.CHANNEL_IN_STEREO, when I use in camcorder mode, i can get access to the second mic but I do not know how to separate the two streams and a numerical value of each stream AudioFormat.ENCODING_PCM_16BIT, bufferSize); – Sriranjan Rasakatla Jul 08 '16 at 11:21