package com.test.mediarecorder;
import java.io.File;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button start, stop;
private MediaRecorder recorder;
private File soundFile;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
start.setOnClickListener(this);
stop.setOnClickListener(this);
recorder = new MediaRecorder();
System.out.println(Environment.getExternalStorageDirectory());
}
@Override
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.start:
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "SD not exists", Toast.LENGTH_LONG).show();
return;
}
// create file to save sound
soundFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile() + "/sound.amr");
// set the sound source
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// set the sound output type it must before set sound encoding
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
//set sound encoding
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(soundFile.getAbsolutePath());
recorder.prepare();
// start record sound
recorder.start();
break;
case R.id.stop:
if (soundFile != null && soundFile.exists()) {
// stop record
recorder.stop();
recorder.release();
recorder = null;
}
break;
}
}catch (Exception e) {
e.printStackTrace();
}
}
}