Android MediaRecorder录音

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;
  }

 }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值