android使用MediaRecorder录音大概步骤:
- 创建 android.media.MediaRecorder实例
- 设置声音来源(MediaRecorder.setAudioSource()),一般使用MediaRecorder.AudioSource.MIC
- 设置输出格式(MediaRecorder.setOutputFormat())
- 设置输出文件(MediaRecorder.setOutputFile())
- 设置声音编码(MediaRecorder.setAudioEncoder())
- 设置完成调用 MediaRecorder.prepare()
- 开始录音MediaRecorder.start()
- 停止录音MediaRecorder.stop()
- 录音完成后调用MediaRecorder.release()释放资源
public class AudioRecord extends AppCompatActivity {
Button record;
Button play;
private MediaRecorder mRecorder = null;
private MediaPlayer player=null;
private String fileName;
private boolean isPlay=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_record);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
iniView();
iniListener();
}
private void iniView(){
record= (Button) findViewById(R.id.record);
play=(Button)findViewById(R.id.play);
}
@Override
protected void onPause() {
super.onPause();
stopPlay();
}
private void iniListener(){
record.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
beginRecord();
break;
case MotionEvent.ACTION_UP:
stopRecord();
break;
}
return true;
}
});
}
//开始录音
private void beginRecord(){
mRecorder=new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
fileName=getFileName(".3gp");
mRecorder.setOutputFile(fileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
System.out.println("start record");
try {
mRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mRecorder.start();
}
//停止录音
private void stopRecord(){
System.out.println("stop record");
if(mRecorder!=null) {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
mRecorder=null;
}
}
//开始播放
private void startPlay(String fileName){
player=new MediaPlayer();
isPlay=true;
try {
player.setDataSource(fileName);
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
}
//停止播放
private void stopPlay(){
if(player!=null){
player.stop();
player.release();
}
isPlay=false;
}
public void play(View v){
System.out.println("clicked");
if(!isPlay)
startPlay(fileName);
else stopPlay();
}
private String getFileName(String format){
String fileName;
fileName = Environment.getExternalStorageDirectory().getAbsolutePath();
fileName += "/"+System.currentTimeMillis()+format;
return fileName;
}
}