小技巧自己记下来,自己用:
因为Android 的录音办法不提供暂停方法,虽然很奇怪,播放有,但是录音和录像都没有这个pause();方法,所以只能自己做暂停,并把每次暂停作为一段完整录音保存下来
在用户点击了最终停止录音的按钮或选项时,把所有录音片段合并,并且删除掉其他录音片段,保留合并的片段,并储存。
重点:
1,只能和并 amr 格式的录音,amr格式的录音片段,开头六个文件头,把所有的录音片段储存到链表里,除了链表第一个开头意外,剩下所有开头文件都删除开头6个字符长度就可。
2,暂时只有amr格式好操作,其他格式会报错
上代码:
/** * 合并录音 * * @param list * @return */ private File getOutputVoiceFile(ArrayList<File> list) { // 创建音频文件,合并的文件放这里 File resFile = new File(ConfigureFile.getInstance().getAUDIO_FILE_NAME()); FileOutputStream fileOutputStream = null; if (!resFile.exists()) { try { resFile.createNewFile(); } catch (IOException e) { } } try { fileOutputStream = new FileOutputStream(resFile); } catch (IOException e) { } // list里面为暂停录音 所产生的 几段录音文件的名字,中间几段文件的减去前面的6个字节头文件 for (int i = 0; i < list.size(); i++) { File file = list.get(i); try { FileInputStream fileInputStream = new FileInputStream(file); byte[] myByte = new byte[fileInputStream.available()]; // 文件长度 int length = myByte.length; // 头文件 if (i == 0) { while (fileInputStream.read(myByte) != -1) { fileOutputStream.write(myByte, 0, length); } } // 之后的文件,去掉头文件就可以了 else { while (fileInputStream.read(myByte) != -1) { fileOutputStream.write(myByte, 6, length - 6); } } fileOutputStream.flush(); fileInputStream.close(); file.delete();//删除其他文件,保留合并后的文件 } catch (Exception e) { e.printStackTrace(); } } // 结束后关闭流 try { fileOutputStream.close(); } catch (IOException e) { } return resFile; }
需要在哪里调用如下:
/** * 停止录音 */ public void stopRecord(){ mRecorder.stop(); File file=getOutputVoiceFile(mRecList); String str=myfile.getName(); file.renameTo(myfile); mRecorder.setOutputFile(file.getAbsolutePath()); mRecorder.release(); mRecorder = null; }当然录音时的办法也不一样:
/** * 储存录音的办法 */ private ArrayList<File> mRecList = new ArrayList<File>(); private MediaRecorder mRecorder; File myfile; public void startRecord(){ mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR); myfile=new File(ConfigureFile.getInstance().getAUDIO_FILE_NAME()); mRecorder.setOutputFile(myfile.getAbsolutePath()); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { mRecorder.prepare(); } catch (IOException e) { e.printStackTrace(); } mRecorder.start(); mRecList.add(myfile); }下面这段路径是我自己需要的路径:
ConfigureFile.getInstance().getAUDIO_FILE_NAME()
这样就可以做到,录音暂停了