How to use getMaxAmplitude - Android - android

I'm working on an App that can record en play audio using the MediaRecorder and MediaPlayer. I also want to display the value of the maxAmplitude. I tried to use the getMaxAmplitude but i cant get it work. it keeps returning 0. The recorder and the player are working properly (it's the from developer.android.com).
Can someone please help me with it.
Eventually i want to display the dB, but i think i can do that by myself once i got this working.
I'm new to android/java, so every help is welcome.
my code
public class AudioRecordTest extends Activity{
private static final String LOG_TAG = "AudioRecordTest";
protected static final String TAG = null;
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private int currentAmplitude;
public boolean activeThread;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
activeThread = true;
mRecorder = null;
}
public void run() {
// TODO Auto-generated method stub
try {
activeThread = true;
while(activeThread){
Log.i(TAG, "onRun()" );
Thread.sleep(50);
threadHandler.sendEmptyMessage(0);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
currentAmplitude = mRecorder.getMaxAmplitude();
Log.i(TAG, "handleMessage : MaxAmplitude : "+Integer.toString(currentAmplitude) );
}
};
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public AudioRecordTest() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
TextView tv = new TextView(this);
ll.addView(tv,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
tv.setText(Integer.toString(currentAmplitude));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}

I'm using this code. I hope it works for you!
private MediaRecorder _recorder;
private MediaPlayer _player;
private Timer _timer;
private String _path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
_timer = new Timer();
prepareEvents();
}
public void prepareEvents() {
try {
Button recordButton = (Button) findViewById(R.id.buttonRecord);
Button stopButton = (Button) findViewById(R.id.buttonStop);
Button playButton = (Button) findViewById(R.id.buttonPlay);
recordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(_recorder == null) {
File downloadFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS);
_path = downloadFolder.getAbsolutePath() + "/test1.aac";
_recorder = new MediaRecorder();
_recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
_recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
_recorder.setAudioSamplingRate(48000);
_recorder.setAudioEncodingBitRate(96000);
_recorder.setAudioChannels(2);
_recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
_recorder.setOutputFile(_path);
_recorder.prepare();
_recorder.start();
_timer.schedule(new TimerTask() {
#Override
public void run() {
RecordActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView) findViewById(R.id.textViewDecibelNumber)).setText(String.valueOf(_recorder.getMaxAmplitude()));
}
});
}
},1000,1000);
}
} catch(Exception exception) {}
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(_recorder != null) {
_recorder.stop();
_recorder.release();
_recorder = null;
_timer.cancel();
((TextView) findViewById(R.id.textViewDecibelNumber)).setText("0");
} else if(_player != null) {
_player.stop();
_player.release();
_player = null;
}
} catch(Exception exception) {}
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(_recorder == null && _path != "") {
_player = new MediaPlayer();
_player.setDataSource(_path);
_player.prepare();
_player.start();
}
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}
});
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}

You should use Thread or Handler to be able to get the max amplitude value at different time. With your code, you actually called the getMaxAmplitude() method just after you start the MediaRecorder, and only once, so it is normal it will give you 0.
Here is some code I used to detect when the sound goes below a specific amplitude : http://pastebin.com/AradRpZm

I do this and it's OK for me.
I hope it help you!
public class MediaRecorder{
private MediaRecorder mRecorder = null;
private Timer timer = new Timer();
File dir;
String file;
public Activity activity;
public void startRecording() {
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(getFilename());
try {
mRecorder.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRecorder.start();
mEMA = 0.0;
}
}
public void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
timer.cancel();
timer.purge();
mRecorder.release();
mRecorder = null;
deleteFile();
}
}
private void deleteFile() {
File sdcard = new File(file);
boolean deleted = sdcard.delete();
Log.i("Deleting File", String.valueOf(deleted));
}
#SuppressLint("SdCardPath")
private String getFilename() {
dir = new File("/sdcard", "AUDIO_RECORDERING");
if (!dir.exists()) {
dir.mkdirs();
}
file = dir.getAbsolutePath() + "/" + System.currentTimeMillis()
+ ".mp3";
return (file);
}
private double getAmplitude() {
if (mRecorder != null) {
double m = mRecorder.getMaxAmplitude();
return (m);
} else {
return 0;
}
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
return amp;
}
}

Related

Real time of device start recording

I use android.media.AudioRecord.
/*initialize AudioRecord*/
long time = System.currentTimeMillis();
audioRecord.startRecording();
When I start audioRecord with method startRecording(), I want to get real time of device start recording. My time is not real...
Please, help me!
Thank you!
Check out this example
long time = System.currentTimeMillis();
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
I think MediaRecorder Will be the better option for recordind Audio and you can record the real time audio.
public class AudioRecordTest extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public AudioRecordTest() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}

recording for a specific interval of time

i want to record an audio input for exactly one second using MediaRecorder. i get an error when i added
handler.postDelayed(..)
here's the code, can anyone tell me how can i fix it? i also tried to do that in seperate threads but it gets complicated when i need to call it from other classes.
public class AudioRecordTest extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private final Handler handler=new Handler();
private void onRecord(boolean start) {
if (start)
startRecording();
handler.postDelayed(new Runnable(){
#Override
public void run()
{
stopRecording();
}
},1000);
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
public AudioRecordTest() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
}
}*

Pause playing record in android

I have a simple class to record voice and playing it after record play file:
public class MainActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private Button startRecord, startPlaying, stopPlaying;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
//stopPlaying();
pausePlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void pausePlaying(){
mPlayer.stop();
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
startPlaying = (Button) findViewById(R.id.buttonStartPlay);
stopPlaying = (Button) findViewById(R.id.buttonStopPlaying);
startRecord = (Button) findViewById(R.id.buttonStartRecord);
startRecord.setOnClickListener(new OnClickListener() {
boolean mStartRecording = true;
#Override
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
startRecord.setText("Stop recording");
} else {
startRecord.setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
startPlaying.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onPlay(true);
}
});
stopPlaying.setOnClickListener(new OnClickListener() {
boolean mStartPlaying = true;
#Override
public void onClick(View v) {
onPlay(false);
}
});
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
I know how can I pause, but I don't know how can I run file again but from moment where I pause my file. Any ideas?
Change this :
private void pausePlaying(){
mPlayer.stop();
}
To:
private void pausePlaying(){
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
}
Don't use .stop() to pause. In the MediaPlayer API you can see that .pause() would be the best option. If you reorganized
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
To happen in your onCreate method you can avoid it resetting every time.
Check out their diagram http://i.stack.imgur.com/svHrq.gif

MediaRecorder instance not released

I am making an android application to record sound. I have been using class MediaRecorder for that.
The recording is done successfully when the recording is done for the first time on any device. But it doesn't work next time.
If I try the code on another machine, recording is done successfully. Is it so because MediaRecorder instance is not getting released by the app even if I am calling method release().
This is my code-
public class NewClass extends Activity {
private static String sFileName = null;
private static String sFileNameMSD = null;
private static String sPlayFile = null;
public MediaRecorder mRecorder = null;
private String mPn_id;
private String mDescription;
private String mTask_flag;
private String mPatient_name;
private String mPatient_id;
private String mIs_upload = "N";
private Context mContext;
Button btnStart;
Button btnStop;
private int mReuqestcode;
NewClass myActivity;
SeekBar seekBar;
int totalTime;
private final Handler handler = new Handler();
private final String FILE_EXTENTION_AMR = ".amr";
private final String FILE_EXTENTION_MSD = ".msd";
protected boolean recodeFlag = false;;
private static final String TAG = GridAllActivity.class.getName();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.transcriptionrecord_activity);
mContext = this;
myActivity = this;
Main.setTitle(myActivity, mContext);
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
mContext));
TextView txtTitle = (TextView) findViewById(R.id.txt_Title1);
txtTitle.setText("Transcription");
TextView txtOption = (TextView) findViewById(R.id.txtOptionName);
TextView txtPatientName = (TextView) findViewById(R.id.txtPatientName);
setProperty();
txtOption.setText("" + mDescription);
txtPatientName.setText("" + mPatient_name);
}
private void onRecord(boolean start) throws SettingNotFoundException {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void startRecording() throws SettingNotFoundException {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
mRecorder.setOutputFile(sFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
recodeFlag=true;
Log.e("1", "prepare() failed");
e.printStackTrace();
}
}
private void stopRecording() throws SettingNotFoundException {
mRecorder.stop();
mRecorder.release();
Log.d("1", "mRecorder released");
mRecorder = null;
System.gc();
}
public void setRecordPath() throws IOException {
sFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
sFileName += Global.creteFolderPath("IMSEMR" + mTask_flag + "_"
+ mPn_id + FILE_EXTENTION_AMR);
sFileNameMSD = "IMSEMR" + mTask_flag + "_" + mPn_id
+ FILE_EXTENTION_MSD;
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
Global.alertbox("", "SD Card is not mounted.", mContext);
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
File directory = new File(sFileName).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
directory.mkdirs();
throw new IOException("Path to file could not be created.");
}
}
public void setRecodingLayout() {
btnStop.setEnabled(false);
try {
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
boolean mStartRecording = true;
try {
btnStop.setEnabled(true);
btnStart.setEnabled(false);
onRecord(mStartRecording);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
}
});
btnStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
boolean mStartRecording = false;
try {
onRecord(mStartRecording);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
} catch (SQLiteException e) {
// TODO: handle exception
} catch (Exception e) {
// TODO: handle exception
}
}
});
} catch (NullPointerException e) {
}
}
public void setProperty() {
Bundle bundel = getIntent().getExtras();
mReuqestcode = (Integer) bundel.get("REQUEST_CODE");
// property for Record
if (mReuqestcode == 1) {
mPn_id = (String) bundel.get("PN_ID");
mDescription = (String) bundel.get("DESCRIPTION");
mTask_flag = (String) bundel.get("TASK_FLAG");
mPatient_id = (String) bundel.get("PATIENT_ID");
mPatient_name = (String) bundel.get("PATIENT_NAME");
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setEnabled(false);
setRecodingLayout();
try {
setRecordPath();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You need to create a new instance of media recorder each time you want to record (making sure to release the previous one).
Update --
Sorry, you only need to create a new instance if you call release on the object. Otherwise you can just call reset,
read this: http://developer.android.com/reference/android/media/MediaRecorder.html
Example:
Lets say you have an activity with 2 buttons, a record button and a play button
public class MyRecordDemo extends Activity {
private static final String PATH_NAME = "/sdcard/myfile.3gp"; //probably shouldn't hardcode this
private Button mRecordButton, mStopButton;
private MediaRecorder mRecorder = null;
private boolean mIsRecording = false;
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.recorder_demo);
mRecordButton = (Button) findViewById(R.id.record_btn);
mStopButton = (Button) findViewById(R.id.stop_btn);
mStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mIsRecording && mRecorder != null) {
mRecorder.stop();
mRecorder.release();
}
}
});
mRecordButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mIsRecording && mRecorder != null) {
mRecorder.stop();
mRecorder.release();
}
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(PATH_NAME);
mRecorder.prepare();
mRecorder.start()
}
});
}
}

Android - How to record simple soundbite?

EDIT: When I click the record button a second time ( to stop recording ) it force closes the app. The specific code for that event:
else if(isrec) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
isrec = false;
Toast.makeText( getApplicationContext(),"No longer recording!",Toast.LENGTH_SHORT).show();
}
(Original question):
I'm having trouble trying to get an app to record sound on a button click. I've included the code... and here's what my Toasts tell me:
after setAudioSource
after setOutputFile
isrec is not true
trying...
caught IO Exception...
Any help is greatly appreciated.
private OnClickListener micListener = new OnClickListener() {
boolean isrec = false;
public void onClick(View v) {
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
Toast.makeText( getApplicationContext(),"after setAudioSource",Toast.LENGTH_SHORT).show();
recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
File outputFile = null;
outputFile = getFileStreamPath("output.amr");
recorder.setOutputFile(outputFile.getAbsolutePath());
Toast.makeText( getApplicationContext(),"after setOutputFile",Toast.LENGTH_SHORT).show();
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
if(!isrec) {
Toast.makeText( getApplicationContext(),"isrec is not true",Toast.LENGTH_SHORT).show();
try {
Toast.makeText( getApplicationContext(),"trying...",Toast.LENGTH_SHORT).show();
recorder.prepare();
recorder.start();
isrec = true;
Toast.makeText( getApplicationContext(),"Recording!",Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText( getApplicationContext(),"caught IllegalState Exception...",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText( getApplicationContext(),"caught IO Exception...",Toast.LENGTH_SHORT).show();
}
} else if(isrec) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
isrec = false;
Toast.makeText( getApplicationContext(),"No longer recording!",Toast.LENGTH_SHORT).show();
}
}
};
First of all, you should use a boolean for isrec instead of a string
That :
FileDescriptor fileName = null;
recorder.setOutputFile(fileName);
That means you want to record on a file which is null
If you create a file, and you pass it as a parameter of your recorder, it should work.
Edit : Sometimes the release doesn't work when you want to stop the recorder.
So, just keep stop() and reset()
Try the following code for the main activity :
public class AudioRecordTestActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public AudioRecordTestActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
and in the manifest file specify the following permissions
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Maybe this will help? The article will show you how to solve two issues:
Show the way to record WAV file.
Record audio with best quality as possible.

Categories

Resources