Android编程录音工具类RecorderUtil定义与用法示例
本文实例讲述了Android编程录音工具类RecorderUtil定义与用法。分享给大家供大家参考,具体如下:
以下工具类都是经过实战开发验证都是可以直接复制使用的。
录音工具类介绍:
录音工具类主要平时用来开发语音聊天的,在微信和QQ上该工具类都是常用的,因为语音聊天。
使用硬件一般都要开权限,别忘了。这里还需要搭配Android FileUtil类使用,为了方便才这么封装的
importandroid.media.MediaRecorder;
importandroid.util.Log;
importjava.io.File;
importjava.io.IOException;
importjava.io.RandomAccessFile;
/**
*录音工具
*/
publicclassRecorderUtil{
privatestaticfinalStringTAG="RecorderUtil";
privateStringmFileName=null;
privateMediaRecordermRecorder=null;
privatelongstartTime;
privatelongtimeInterval;
privatebooleanisRecording;
publicRecorderUtil(){
mFileName=FileUtil.getCacheFilePath("tempAudio");
}
/**
*开始录音
*/
publicvoidstartRecording(){
if(mFileName==null)return;
if(isRecording){
mRecorder.release();
mRecorder=null;
}
mRecorder=newMediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
startTime=System.currentTimeMillis();
try{
mRecorder.prepare();
mRecorder.start();
isRecording=true;
}catch(Exceptione){
Log.e(TAG,"prepare()failed");
}
}
/**
*停止录音
*/
publicvoidstopRecording(){
if(mFileName==null)return;
timeInterval=System.currentTimeMillis()-startTime;
try{
if(timeInterval>1000){
mRecorder.stop();
}
mRecorder.release();
mRecorder=null;
isRecording=false;
}catch(Exceptione){
Log.e(TAG,"release()failed");
}
}
/**
*取消语音
*/
publicsynchronizedvoidcancelRecording(){
if(mRecorder!=null){
try{
mRecorder.release();
mRecorder=null;
}catch(Exceptione){
e.printStackTrace();
}
Filefile=newFile(mFileName);
file.deleteOnExit();
}
isRecording=false;
}
/**
*获取录音文件
*/
publicbyte[]getDate(){
if(mFileName==null)returnnull;
try{
returnreadFile(newFile(mFileName));
}catch(IOExceptione){
Log.e(TAG,"readfileerror"+e);
returnnull;
}
}
/**
*获取录音文件地址
*/
publicStringgetFilePath(){
returnmFileName;
}
/**
*获取录音时长,单位秒
*/
publiclonggetTimeInterval(){
returntimeInterval/1000;
}
/**
*将文件转化为byte[]
*
*@paramfile输入文件
*/
privatestaticbyte[]readFile(Filefile)throwsIOException{
//Openfile
RandomAccessFilef=newRandomAccessFile(file,"r");
try{
//Getandchecklength
longlonglength=f.length();
intlength=(int)longlength;
if(length!=longlength)
thrownewIOException("Filesize>=2GB");
//Readfileandreturndata
byte[]data=newbyte[length];
f.readFully(data);
returndata;
}finally{
f.close();
}
}
}
使用步骤:
1.首先privateRecorderUtilrecorder=newRecorderUtil();实例化一下
2.开始录音recorder.startRecording();
3.录音完成后停止录音recorder.stopRecording();
4.当然如果录音开始之后想取消语音发送,类似于微信上滑取消语音发送,解决方案滑动监听判断确定取消发送,就不要将消息发出去并且还要调用recorder.cancelRecording();//取消语音释放资源即可
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android操作json格式数据技巧总结》、《Android资源操作技巧汇总》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。