Android使用AudioRecord实现暂停录音功能实例代码
程序员文章站
2022-06-11 09:29:40
题外话:发现好久都没有上来写博文了,毕业设计加上公司暂时没有android的项目做,只能去自学web上的知识,摸爬打滚到现在,花了一个多月时间根据公司的现有模板做了公司内部...
题外话:发现好久都没有上来写博文了,毕业设计加上公司暂时没有android的项目做,只能去自学web上的知识,摸爬打滚到现在,花了一个多月时间根据公司的现有模板做了公司内部一个任务管理系统,感觉都是比较浅的知识,没什么可以写的。想到之前做的语音识别的项目,虽然现在没什么下文了,但是谁懂~~~将来呢?
言归正传,项目长这样子:
设计的思路:
由于自带的audiorecord没有pauserecord()方法,我把开始录音-->(暂停/继续录音)...-->停止录音叫做一次录音,点击一次暂停就会产生一个文件(.pcm),将一次录音产生的所有文件名(.pcm)用一个list装起来,点击停止后将遍历list取得所有文件路径进行拼接。
由于考虑到以后可能要进行语音识别,所以对程序的灵活性和拓展性都做了相应的处理,可以通过setlistener()监听录音的音频流和监听录音结束。
采用线程池对线程进行管理,减少系统开销。
对类的说明:
- audiorecorder:封装了录音的方法:创建录音对象、开始、暂停、停止、取消,使用静态枚举类status来记录录音的状态。
- fileutils:文件工具类,用于文件路径的获取
- pcmtowav:封装了将.pcm文件转化.wav文件的方法
- waveheader: wav文件头
- recordstreamlistener:监听录音音频流,用于拓展业务的处理
接下来是关键代码部分:
1、audiorecorder类:
package com.hxl.pauserecord.record; import android.media.audioformat; import android.media.audiorecord; import android.media.mediarecorder; import android.text.textutils; import android.util.log; import java.io.file; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.util.arraylist; import java.util.list; import java.util.concurrent.executorservice; import java.util.concurrent.executors; /** * created by hxl on 16/8/11. * 用于实现录音 暂停录音 */ public class audiorecorder { //音频输入-麦克风 private final static int audio_input = mediarecorder.audiosource.mic; //采用频率 //44100是目前的标准,但是某些设备仍然支持22050,16000,11025 //采样频率一般共分为22.05khz、44.1khz、48khz三个等级 private final static int audio_sample_rate = 16000; //声道 单声道 private final static int audio_channel = audioformat.channel_in_mono; //编码 private final static int audio_encoding = audioformat.encoding_pcm_16bit; // 缓冲区字节大小 private int buffersizeinbytes = 0; //录音对象 private audiorecord audiorecord; //录音状态 private status status = status.status_no_ready; //文件名 private string filename; //录音文件 private list<string> filesname = new arraylist<>(); //线程池 private executorservice mexecutorservice; //录音监听 private recordstreamlistener listener; public audiorecorder() { mexecutorservice = executors.newcachedthreadpool(); } /** * 创建录音对象 */ public void createaudio(string filename, int audiosource, int samplerateinhz, int channelconfig, int audioformat) { // 获得缓冲区字节大小 buffersizeinbytes = audiorecord.getminbuffersize(samplerateinhz, channelconfig, channelconfig); audiorecord = new audiorecord(audiosource, samplerateinhz, channelconfig, audioformat, buffersizeinbytes); this.filename = filename; } /** * 创建默认的录音对象 * * @param filename 文件名 */ public void createdefaultaudio(string filename) { // 获得缓冲区字节大小 buffersizeinbytes = audiorecord.getminbuffersize(audio_sample_rate, audio_channel, audio_encoding); audiorecord = new audiorecord(audio_input, audio_sample_rate, audio_channel, audio_encoding, buffersizeinbytes); this.filename = filename; status = status.status_ready; } /** * 开始录音 * */ public void startrecord() { if (status == status.status_no_ready||audiorecord==null) { throw new illegalstateexception("录音尚未初始化,请检查是否禁止了录音权限~"); } if (status == status.status_start) { throw new illegalstateexception("正在录音"); } log.d("audiorecorder", "===startrecord===" + audiorecord.getstate()); audiorecord.startrecording(); string currentfilename = filename; if (status == status.status_pause) { //假如是暂停录音 将文件名后面加个数字,防止重名文件内容被覆盖 currentfilename += filesname.size(); } filesname.add(currentfilename); final string finalfilename=currentfilename; //将录音状态设置成正在录音状态 status = status.status_start; //使用线程池管理线程 mexecutorservice.execute(new runnable() { @override public void run() { writedatatofile(finalfilename); } }); } /** * 暂停录音 */ public void pauserecord() { log.d("audiorecorder", "===pauserecord==="); if (status != status.status_start) { throw new illegalstateexception("没有在录音"); } else { audiorecord.stop(); status = status.status_pause; } } /** * 停止录音 */ public void stoprecord() { log.d("audiorecorder", "===stoprecord==="); if (status == status.status_no_ready || status == status.status_ready) { throw new illegalstateexception("录音尚未开始"); } else { audiorecord.stop(); status = status.status_stop; release(); } } /** * 释放资源 */ public void release() { log.d("audiorecorder", "===release==="); //假如有暂停录音 try { if (filesname.size() > 0) { list<string> filepaths = new arraylist<>(); for (string filename : filesname) { filepaths.add(fileutils.getpcmfileabsolutepath(filename)); } //清除 filesname.clear(); //将多个pcm文件转化为wav文件 mergepcmfilestowavfile(filepaths); } else { //这里由于只要录音过filesname.size都会大于0,没录音时filename为null //会报空指针 nullpointerexception // 将单个pcm文件转化为wav文件 //log.d("audiorecorder", "=====makepcmfiletowavfile======"); //makepcmfiletowavfile(); } } catch (illegalstateexception e) { throw new illegalstateexception(e.getmessage()); } if (audiorecord != null) { audiorecord.release(); audiorecord = null; } status = status.status_no_ready; } /** * 取消录音 */ public void canel() { filesname.clear(); filename = null; if (audiorecord != null) { audiorecord.release(); audiorecord = null; } status = status.status_no_ready; } /** * 将音频信息写入文件 * */ private void writedatatofile(string currentfilename) { // new一个byte数组用来存一些字节数据,大小为缓冲区大小 byte[] audiodata = new byte[buffersizeinbytes]; fileoutputstream fos = null; int readsize = 0; try { file file = new file(fileutils.getpcmfileabsolutepath(currentfilename)); if (file.exists()) { file.delete(); } fos = new fileoutputstream(file);// 建立一个可存取字节的文件 } catch (illegalstateexception e) { log.e("audiorecorder", e.getmessage()); throw new illegalstateexception(e.getmessage()); } catch (filenotfoundexception e) { log.e("audiorecorder", e.getmessage()); } while (status == status.status_start) { readsize = audiorecord.read(audiodata, 0, buffersizeinbytes); if (audiorecord.error_invalid_operation != readsize && fos != null) { try { fos.write(audiodata); if (listener != null) { //用于拓展业务 listener.onrecording(audiodata, 0, audiodata.length); } } catch (ioexception e) { log.e("audiorecorder", e.getmessage()); } } } if (listener != null) { listener.finishrecord(); } try { if (fos != null) { fos.close();// 关闭写入流 } } catch (ioexception e) { log.e("audiorecorder", e.getmessage()); } } /** * 将pcm合并成wav * * @param filepaths */ private void mergepcmfilestowavfile(final list<string> filepaths) { mexecutorservice.execute(new runnable() { @override public void run() { if (pcmtowav.mergepcmfilestowavfile(filepaths, fileutils.getwavfileabsolutepath(filename))) { //操作成功 } else { //操作失败 log.e("audiorecorder", "mergepcmfilestowavfile fail"); throw new illegalstateexception("mergepcmfilestowavfile fail"); } } }); } /** * 将单个pcm文件转化为wav文件 */ private void makepcmfiletowavfile() { mexecutorservice.execute(new runnable() { @override public void run() { if (pcmtowav.makepcmfiletowavfile(fileutils.getpcmfileabsolutepath(filename), fileutils.getwavfileabsolutepath(filename), true)) { //操作成功 } else { //操作失败 log.e("audiorecorder", "makepcmfiletowavfile fail"); throw new illegalstateexception("makepcmfiletowavfile fail"); } } }); } /** * 录音对象的状态 */ public enum status { //未开始 status_no_ready, //预备 status_ready, //录音 status_start, //暂停 status_pause, //停止 status_stop } /** * 获取录音对象的状态 * * @return */ public status getstatus() { return status; } /** * 获取本次录音文件的个数 * * @return */ public int getpcmfilescount() { return filesname.size(); } public recordstreamlistener getlistener() { return listener; } public void setlistener(recordstreamlistener listener) { this.listener = listener; } }
2:pcmtowav
package com.hxl.pauserecord.record; import android.util.log; import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.text.simpledateformat; import java.util.arraylist; import java.util.date; import java.util.list; /** * created by hxl on 16/8/11. * 将pcm文件转化为wav文件 */ public class pcmtowav { /** * 合并多个pcm文件为一个wav文件 * * @param filepathlist pcm文件路径集合 * @param destinationpath 目标wav文件路径 * @return true|false */ public static boolean mergepcmfilestowavfile(list<string> filepathlist, string destinationpath) { file[] file = new file[filepathlist.size()]; byte buffer[] = null; int total_size = 0; int filenum = filepathlist.size(); for (int i = 0; i < filenum; i++) { file[i] = new file(filepathlist.get(i)); total_size += file[i].length(); } // 填入参数,比特率等等。这里用的是16位单声道 8000 hz waveheader header = new waveheader(); // 长度字段 = 内容的大小(total_size) + // 头部字段的大小(不包括前面4字节的标识符riff以及filelength本身的4字节) header.filelength = total_size + (44 - 8); header.fmthdrleth = 16; header.bitspersample = 16; header.channels = 2; header.formattag = 0x0001; header.samplespersec = 8000; header.blockalign = (short) (header.channels * header.bitspersample / 8); header.avgbytespersec = header.blockalign * header.samplespersec; header.datahdrleth = total_size; byte[] h = null; try { h = header.getheader(); } catch (ioexception e1) { log.e("pcmtowav", e1.getmessage()); return false; } if (h.length != 44) // wav标准,头部应该是44字节,如果不是44个字节则不进行转换文件 return false; //先删除目标文件 file destfile = new file(destinationpath); if (destfile.exists()) destfile.delete(); //合成所有的pcm文件的数据,写到目标文件 try { buffer = new byte[1024 * 4]; // length of all files, total size inputstream instream = null; outputstream oustream = null; oustream = new bufferedoutputstream(new fileoutputstream( destinationpath)); oustream.write(h, 0, h.length); for (int j = 0; j < filenum; j++) { instream = new bufferedinputstream(new fileinputstream(file[j])); int size = instream.read(buffer); while (size != -1) { oustream.write(buffer); size = instream.read(buffer); } instream.close(); } oustream.close(); } catch (filenotfoundexception e) { log.e("pcmtowav", e.getmessage()); return false; } catch (ioexception ioe) { log.e("pcmtowav", ioe.getmessage()); return false; } clearfiles(filepathlist); log.i("pcmtowav", "mergepcmfilestowavfile success!" + new simpledateformat("yyyy-mm-dd hh:mm").format(new date())); return true; } /** * 将一个pcm文件转化为wav文件 * * @param pcmpath pcm文件路径 * @param destinationpath 目标文件路径(wav) * @param deletepcmfile 是否删除源文件 * @return */ public static boolean makepcmfiletowavfile(string pcmpath, string destinationpath, boolean deletepcmfile) { byte buffer[] = null; int total_size = 0; file file = new file(pcmpath); if (!file.exists()) { return false; } total_size = (int) file.length(); // 填入参数,比特率等等。这里用的是16位单声道 8000 hz waveheader header = new waveheader(); // 长度字段 = 内容的大小(total_size) + // 头部字段的大小(不包括前面4字节的标识符riff以及filelength本身的4字节) header.filelength = total_size + (44 - 8); header.fmthdrleth = 16; header.bitspersample = 16; header.channels = 2; header.formattag = 0x0001; header.samplespersec = 8000; header.blockalign = (short) (header.channels * header.bitspersample / 8); header.avgbytespersec = header.blockalign * header.samplespersec; header.datahdrleth = total_size; byte[] h = null; try { h = header.getheader(); } catch (ioexception e1) { log.e("pcmtowav", e1.getmessage()); return false; } if (h.length != 44) // wav标准,头部应该是44字节,如果不是44个字节则不进行转换文件 return false; //先删除目标文件 file destfile = new file(destinationpath); if (destfile.exists()) destfile.delete(); //合成所有的pcm文件的数据,写到目标文件 try { buffer = new byte[1024 * 4]; // length of all files, total size inputstream instream = null; outputstream oustream = null; oustream = new bufferedoutputstream(new fileoutputstream( destinationpath)); oustream.write(h, 0, h.length); instream = new bufferedinputstream(new fileinputstream(file)); int size = instream.read(buffer); while (size != -1) { oustream.write(buffer); size = instream.read(buffer); } instream.close(); oustream.close(); } catch (filenotfoundexception e) { log.e("pcmtowav", e.getmessage()); return false; } catch (ioexception ioe) { log.e("pcmtowav", ioe.getmessage()); return false; } if (deletepcmfile) { file.delete(); } log.i("pcmtowav", "makepcmfiletowavfile success!" + new simpledateformat("yyyy-mm-dd hh:mm").format(new date())); return true; } /** * 清除文件 * * @param filepathlist */ private static void clearfiles(list<string> filepathlist) { for (int i = 0; i < filepathlist.size(); i++) { file file = new file(filepathlist.get(i)); if (file.exists()) { file.delete(); } } } }
3、waveheader类:
package com.hxl.pauserecord.record; import java.io.bytearrayoutputstream; import java.io.ioexception; /** * created by hxl on 16/3/9. * wav文件头 */ public class waveheader { public final char fileid[] = {'r', 'i', 'f', 'f'}; public int filelength; public char wavtag[] = {'w', 'a', 'v', 'e'};; public char fmthdrid[] = {'f', 'm', 't', ' '}; public int fmthdrleth; public short formattag; public short channels; public int samplespersec; public int avgbytespersec; public short blockalign; public short bitspersample; public char datahdrid[] = {'d','a','t','a'}; public int datahdrleth; public byte[] getheader() throws ioexception { bytearrayoutputstream bos = new bytearrayoutputstream(); writechar(bos, fileid); writeint(bos, filelength); writechar(bos, wavtag); writechar(bos, fmthdrid); writeint(bos,fmthdrleth); writeshort(bos,formattag); writeshort(bos,channels); writeint(bos,samplespersec); writeint(bos,avgbytespersec); writeshort(bos,blockalign); writeshort(bos,bitspersample); writechar(bos,datahdrid); writeint(bos,datahdrleth); bos.flush(); byte[] r = bos.tobytearray(); bos.close(); return r; } private void writeshort(bytearrayoutputstream bos, int s) throws ioexception { byte[] mybyte = new byte[2]; mybyte[1] =(byte)( (s << 16) >> 24 ); mybyte[0] =(byte)( (s << 24) >> 24 ); bos.write(mybyte); } private void writeint(bytearrayoutputstream bos, int n) throws ioexception { byte[] buf = new byte[4]; buf[3] =(byte)( n >> 24 ); buf[2] =(byte)( (n << 8) >> 24 ); buf[1] =(byte)( (n << 16) >> 24 ); buf[0] =(byte)( (n << 24) >> 24 ); bos.write(buf); } private void writechar(bytearrayoutputstream bos, char[] id) { for (int i=0; i<id.length; i++) { char c = id[i]; bos.write(c); } } }
接下来是效果图。。。个人为人做app界面一定要美观,而且要非常美观,不然谁会用你的东西!so~~
好吧,请大家撇开ui看功能~正如预期的一样,每点击暂停一次会生成一个pcm文件,当点击停止的时候,将所有的录音整合成一个可播放的.wav文件
接下来,项目源码:点击下载
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Unity3D 残影效果