赞
踩
在新的项目需求中要求做一个类似QQ按住说话语音功能,第一时间想到的是用service搭配MediaRecorder实现录音功能,听着歌快乐的搞定了(基本上OK了),小组开发的说帮忙处理下,于是回过头来看时里面的格式什么的都上升了几个档次,瞬间被羞愧了。然后就给我说录音还是有问题:
1. 当前录音的发送得到的录音地址是上一次的录音,原因是采用SharedPreferences存放当前录音文件路径和文件URL是在MediaRecorder的stop()方法之后,主线程中拿去这个SharedPreferences存放的值是在录音处理的services的topService(Activity)之后去处理的,这造成了主线程这边关闭这个service后拿录音文件地址是在真实的service的Destory()方法之前的,以至于真实的当前录音此时还未存放,当然就会bug了,所以在考虑使用SharedPreferences情况下就在Service的topService(Activity)和Destory()方法中MediaRecorder的stop()方法后存当前录音文件后调用一次EventBus,最后在拿去数据的时候调用一次该方法,保证拿到当前的文件;
2. 由于是长按触发录音,松开触发发送事件,所以一不注意就很容易造成MediaRecorder的stop()方法造成-19错误。这是因为控件点击时间过短对MediaRecorder的监听和对象为空造成的,已证明测试可行的方法是对MediaRecorder.stop()抛出异常,即为:
MediaRecorder mRecorder = new MediaRecorder(); //在启用录音时一定要声明MediaRecorder 的对象 mRecorder.setOnErrorListener(null); mRecorder.setOnInfoListener(null); mRecorder.setPreviewDisplay(null); try { mRecorder.stop(); //这是对录音文件的时长和文件保存处理,可忽视 mElapsedMillis = (System.currentTimeMillis() - mStartingTimeMillis); mRecorder.release(); getSharedPreferences("sp_name_audio", MODE_PRIVATE) .edit() .putString("audio_path", mFilePath) .putLong("elpased", mElapsedMillis) .apply(); if (mIncrementTimerTask != null) { mIncrementTimerTask.cancel(); mIncrementTimerTask = null; } mRecorder = null; } catch (IllegalStateException e) { ToastUtil.showShort(mActivity,"按键时间太短!"); e.printStackTrace(); }catch (RuntimeException e) { ToastUtil.showShort(mActivity,"按键时间太短!"); e.printStackTrace(); } catch (Exception e) { ToastUtil.showShort(mActivity,"按键时间太短!"); e.printStackTrace(); } mRecorder.release(); mRecorder = null; }
暂时就这些,若还有可补充的会另写一个较详细的记录
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。