仿微信语音录制

来源:互联网 发布:涉案账户资金网络查控 编辑:程序博客网 时间:2024/06/05 06:25

1. 设置按钮的TouchListener

but_audio.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) { // 判断当前点击状态case MotionEvent.ACTION_DOWN: // 按下mSoundPool.play(down_music, 1, 1, 0, 0, 1); // 播放按钮铃声if (!isRecordingAudio) { // 判断不处于录音状态// 计算出上次开始时间和本次开始录音时间间隔,如果小于1S,提示用户,不录音long intervalTime = System.currentTimeMillis()- startTime;if (intervalTime < 1000) {Toast.makeText(MessageActivity.this, "操作太频繁,请稍后使用",0).show();return false;}RecordingAudio();}break;case MotionEvent.ACTION_UP: // 移开if (isRecordingAudio) {new Thread() {public void run() {SystemClock.sleep(100); // 睡一会,在停止录音mMediaRecorder.stop(); // 停止录音mMediaRecorder.release(); // 释放资源mMediaRecorder = null; // 回收message = new Message();message.what = 1;mHandler.sendMessage(message);};}.start();}isRecordingAudio = false;break;case MotionEvent.ACTION_MOVE: // 滑动break;}return false;}});


2. handler处理录音消息


private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:long stopTime = System.currentTimeMillis() - startTime;if (stopTime < 1000) {Toast.makeText(MessageActivity.this, "录音时间太短,无法发送", 0).show();deleteAudioFile(fileName);} else {intendFileUpload();mFileUpload.setFile(myRecAudioFile);mFileUpload.setMessageType(SycConstant.Message_Type_sound);// 发送语音消息mFileUpload.startUpLoad();MessageActivity.this.sendMessage(SycConstant.Message_Type_sound, GloableParameters.DIR_PATH + fileName);mSoundPool.play(up_music, 1, 1, 0, 0, 1); // 播放按钮铃声}break;case 2:getData();break;}}};

3. 提示音的初始化


private SoundPool mSoundPool; // 声明一个SoundPool,用来播放一段语音private int down_music; // 定义一个整型用load();来设置suondIDprivate int up_music; // 松开的声音mSoundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);// 第一个参数为同时播放数据流的最大个数,第二数据流类型,第三为声音质量down_music = mSoundPool.load(getApplicationContext(), R.raw.down_audio,1); // 把你的声音素材放到res/raw里,第2个参数即为资源文件,第3个为音乐的优先级up_music = mSoundPool.load(getApplicationContext(), R.raw.up_audio, 1);

4. 录音的方法


/** * 录音 */private void RecordingAudio() {File myRecAudioDir = new File(GloableParameters.DIR_PATH); // 创建录音文件存储目录try {myRecAudioFile = File.createTempFile(String.valueOf(System.currentTimeMillis()) ,".amr", myRecAudioDir); // 创建录音文件fileName = myRecAudioFile.getName();mMediaRecorder = new MediaRecorder();mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 第1步:设置音频来源(MIC表示麦克风)mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // 第2步:设置音频输出格式(默认的输出格式)mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); // 第3步:设置音频编码方式(默认的编码方式)mMediaRecorder.setOutputFile(myRecAudioFile.getAbsolutePath()); // 第4步:指定音频输出文件mMediaRecorder.prepare(); // 第5步:调用prepare方法if (!isRecordingAudio) { // 判断当前是否处于录音状态mMediaRecorder.start(); // 第6步:调用start方法开始录音startTime = System.currentTimeMillis(); // 记录开启录音时间isRecordingAudio = true; // 记录录音状态}} catch (IOException e) {// 录音出现异常}}






0 0
原创粉丝点击