今天工作上需要做一个仿微信语音聊天中的按住说话的功能。其实很简单,主要就是利用MediaRecorder实现录音,用MediaPlayer实现播放功能。下面我就具体说一下是怎么实现的。
1,首先对按钮的onTouch事件进行监听。
mBtnVoice.setText("按住说话");
mBtnVoice.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startVoice();
break;
case MotionEvent.ACTION_UP:
stopVoice();
break;
default:
break;
}
return false;
}
});
当按下的时候,开始进行录音,
/** 开始录音 */
private void startVoice() {
// 设置录音保存路径
mFileName = PATH + UUID.randomUUID().toString() + ".amr";
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(andro