Android MediaRecorder录音具体实现代码如下:
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "RECORD_TAG";
private String fileSavePath = null;
private String fileName = null;
private String recFilePath = null;
private Button btnStartRec, btnStopRec, btnPlayRec, btnStopPlay;
private MediaPlayer mPlayer = null;
private MediaRecorder mRecorder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStartRec = (Button) findViewById(R.id.btnStartRec);
btnStopRec = (Button) findViewById(R.id.btnStopRec);
btnPlayRec = (Button) findViewById(R.id.btnPlayRec);
btnStopPlay = (Button) findViewById(R.id.btnStopPlay);
btnStartRec.setOnClickListener(this);
btnStopRec.setOnClickListener(this);
btnPlayRec.setOnClickListener(this);
btnStopPlay.setOnClickListener(this);
fileSavePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Record/";
File f = new File(fileSavePath);
if (!f.exists()) {
f.mkdirs();
}
}
//创建文件名
private String createFileName() {
return String.valueOf(System.currentTimeMillis()) + ".3gp";
}
private void startRecord() {
fileName = createFileName();
recFilePath = fileSavePath + fileName;
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(recFilePath);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
mRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void stopRecord() {
try {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
} catch (Exception e) {
e.printStackTrace();
}
}
private void playRecord() {
try {
mPlayer = new MediaPlayer();
mPlayer.setDataSource(recFilePath);
mPlayer.prepare();
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void stopPlayRecord() {
try {
mPlayer.release();
mPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartRec:
startRecord();
break;
case R.id.btnStopRec:
stopRecord();
break;
case R.id.btnPlayRec:
playRecord();
break;
case R.id.btnStopPlay:
stopPlayRecord();
break;
default:
break;
}
}
}