AndroidManifest先添加两个权限
代码:转自:http://blog.csdn.net/cxf7394373/article/details/8313980
Boolean isRecstop = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//开始录音
startRecord = (Button)findViewById(R.id.startRecord);
startRecord.setText(R.string.startRecord);
//绑定监听器
startRecord.setOnClickListener(new startRecordListener());
//结束录音
stopRecord = (Button)findViewById(R.id.stopRecord);
stopRecord.setText(R.string.stopRecord);
stopRecord.setOnClickListener(new stopRecordListener());
//开始播放
startPlay = (Button)findViewById(R.id.startPlay);
startPlay.setText(R.string.startPlay);
//绑定监听器
startPlay.setOnClickListener(new startPlayListener());
//结束播放
stopPlay = (Button)findViewById(R.id.stopPlay);
stopPlay.setText(R.string.stopPlay);
stopPlay.setOnClickListener(new stopPlayListener());
//设置sdcard的路径
FileName = Environment.getExternalStorageDirectory().getAbsolutePath();
FileName += "/audiorecordtest.3gp";
}
//开始录音
class startRecordListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(FileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
}
//停止录音
class stopRecordListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!isRecstop){
mRecorder.stop();
}
isRecStop = true;
}
}
//播放录音
class startPlayListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mPlayer = new MediaPlayer();
try{
mPlayer.setDataSource(FileName);
mPlayer.prepare();
mPlayer.start();
}catch(IOException e){
Log.e(LOG_TAG,"播放失败");
}
}
}
//停止播放录音
class stopPlayListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mPlayer.release();
mPlayer = null;
}
}
}