java代码
public class RecordSound extends Activity
implements OnClickListener
{
Button record , stop;
File soundFile ;
MediaRecorder mRecorder;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recordsound);
record = (Button) findViewById(R.id.record);
stop = (Button) findViewById(R.id.stop);
stop.setEnabled(false);
record.setOnClickListener(this);
stop.setOnClickListener(this);
}
public void onClick(View source)
{
switch (source.getId())
{
case R.id.record:
if (!Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
{
Toast.makeText(RecordSound.this
, "SD卡不存在,请插入SD卡!"
, 5000)
.show();
return;
}
try
{
Date date=null;
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
date =new Date();
String str=format.format(date);
String fileName =SceneRecord.tempfilestr+"/"+str+".mp3";
soundFile = new File(fileName);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder
.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder
.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(soundFile.getAbsolutePath());
mRecorder.prepare();
mRecorder.start();
record.setEnabled(false);
stop.setEnabled(true);
}
catch (Exception e)
{
e.printStackTrace();
}
break;
case R.id.stop:
if (soundFile != null && soundFile.exists())
{
mRecorder.stop();
mRecorder.release();
mRecorder = null;
record.setEnabled(true);
stop.setEnabled(false);
RecordSound.this.finish();
Intent intent = new Intent(RecordSound.this,AddAccidentRecord.class);
startActivity(intent);
}
break;
}
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<Button
android:id="@+id/record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="录制"
/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存"
/>
</LinearLayout>
权限
<uses-permission android:name="android.permission.RECORD_AUDIO"/>