Android仿微信发送语音消息的功能及示例代码
时间:2020-12-19 10:45:13|栏目:Android代码|点击: 次
微信的发送语音是有一个向上取消的,我们使用onTouchListener
来监听手势,然后做出相应的操作就行了。
直接上代码:
//语音操作对象 private MediaPlayer mPlayer = null; private MediaRecorder mRecorder = null; //语音文件保存路径 private String FileName = null; FileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/soundrecord/amrsend.amr";
定义一个ImageView,然后给它设置监听事件:
@Override public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: beginX = motionEvent.getX(); beginY = motionEvent.getY(); Log.e("MainActivity", "beginX:" + beginX); Log.e("MainActivity", "beginY:" + beginY); Log.e("MainActivity", "ACTION_DOWN"); 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(); } catch (IOException e) { Log.e("MainActivity", "prepare() failed" + e); } mRecorder.start(); break; case MotionEvent.ACTION_UP: finalX = motionEvent.getX(); finalY = motionEvent.getY(); Log.e("MainActivity", "finalX:" + finalX); Log.e("MainActivity", "finalY:" + finalY); Log.e("MainActivity", "ACTION_UP"); mRecorder.stop(); mRecorder.release(); mRecorder = null; if ((beginY - finalY) > 50) { Log.e("MainActivity", "执行删除"); new File(FileName).delete(); Log.e("MainActivity", "执行删除后文件是否还存在:" + new File(FileName).exists()); } break; default: break; } return true; }
然后在清单文件中加上需要的权限就行了:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" />
也可以在按下之后播放动画,显示正在录音,然后在抬起动作之后结束动画,这样就比较形象了。
总结