xfcyhades 2011-06-16
importjava.io.File;
importjava.io.IOException;
importjava.util.Calendar;
importjava.util.Locale;
importandroid.app.Activity;
importandroid.media.MediaRecorder;
importandroid.os.Bundle;
importandroid.text.format.DateFormat;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.Toast;
publicclassMainActivityextendsActivity{
privateButtonrecordButton;
privateButtonstopButton;
privateMediaRecordermr;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
recordButton=(Button)this.findViewById(R.id.Button01);
stopButton=(Button)this.findViewById(R.id.Button02);
//录音按钮点击事件
recordButton.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
Filefile=newFile("/sdcard/"+"YY"+newDateFormat().format("yyyyMMdd_HHmmss",Calendar.getInstance(Locale.CHINA))+".amr");
Toast.makeText(getApplicationContext(),"正在录音,录音文件在"+file.getAbsolutePath(),Toast.LENGTH_LONG)
.show();
//创建录音对象
mr=newMediaRecorder();
//从麦克风源进行录音
mr.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
//设置输出格式
mr.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
//设置编码格式
mr.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
//设置输出文件
mr.setOutputFile(file.getAbsolutePath());
try{
//创建文件
file.createNewFile();
//准备录制
mr.prepare();
}catch(IllegalStateExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
//开始录制
mr.start();
recordButton.setText("录音中……");
}
});
//停止按钮点击事件
stopButton.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
if(mr!=null){
mr.stop();
mr.release();
mr=null;
recordButton.setText("录音");
Toast.makeText(getApplicationContext(),"录音完毕",Toast.LENGTH_LONG).show();
}
}
});
}
}
<uses-permissionandroid:name="android.permission.RECORD_AUDIO"></uses-permission>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>