参考以下,
public class AudioRecordingActivity extends Activity implements OnClickListener{
MediaRecorder recorder;
final String fileNameStr = "audio-android.3gp";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.btn_record)).setOnClickListener(this);
((Button) findViewById(R.id.btn_stop)).setOnClickListener(this);
((Button) findViewById(R.id.btn_play)).setOnClickListener(this);
}
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_record: {
System.out.println("Record pressed.");
try {
recorder = new MediaRecorder();
FileOutputStream fos = openFileOutput(fileNameStr, MODE_PRIVATE);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(fos.getFD());
recorder.prepare();
recorder.start();
} catch (IOException e) {
System.out.println("IOException caught during recording.");
e.printStackTrace();
}
return;
}
case R.id.btn_stop: {
recorder.stop();
recorder.release();
System.out.println("Stop pressed.");
return;
}
case R.id.btn_play: {
System.out.println("Play pressed.");
MediaPlayer mp = new MediaPlayer();
try {
FileInputStream fis = openFileInput(fileNameStr);
mp.setDataSource(fis.getFD());
mp.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
return;
}
}
}
}
主要的.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/start" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stop" />
<Button
android:id="@+id/btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/play" />
</LinearLayout>