Android仿微信录音功能(录音后的raw文件转mp3文件)
现在很多时候需要用到录音,然后如果我们的App是ios和android两端的话,就要考虑录音的文件在两端都能使用,这个时候就需要适配,两端的录音文件都要是mp3文件,这样才能保证两边都能播放。
针对这个,封装了一个简单可用的录音控件。
使用方法:
1.在xml文件中添加
2.别忘了申请录音权限
AndPermission.with(MainActivity.this)
.permission(Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
.onGranted(permissions->{
showSelect();
})
.onDenied(permissions->{
Toast.makeText(MainActivity.this,"请同意录音权限",Toast.LENGTH_SHORT).show();
})
.start();
privatevoidshowSelect(){
SoundTextViewrecordAudio=findViewById(R.id.record_audio);
recordAudio.setOnRecordFinishedListener(newSoundTextView.OnRecordFinishedListener(){
@Override
publicvoidnewMessage(Stringpath,intduration){
intindex=path.lastIndexOf("/");
StringfileName=path.substring(index+1);
Log.e("录音文件","path=:"+path);
}
});
}
使用方法如上非常简单:
主要的类
packageant.muxi.com.audiodemo.view;
importandroid.app.Activity;
importandroid.app.Dialog;
importandroid.content.Context;
importandroid.os.Environment;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.util.AttributeSet;
importandroid.util.Log;
importandroid.view.MotionEvent;
importandroid.widget.TextView;
importandroid.widget.Toast;
importandroidx.appcompat.widget.AppCompatTextView;
importjava.io.File;
important.muxi.com.audiodemo.R;
important.muxi.com.audiodemo.audio.ProgressTextUtils;
important.muxi.com.audiodemo.audio.RecordManager;
publicclassSoundTextViewextendsAppCompatTextView{
privateContextmContext;
privateDialogrecordIndicator;
privateTextViewmVoiceTime;
privateFilefile;
privateStringtype="1";//默认开始录音type=2,录音完毕
RecordManagerrecordManager;
Filefileto;
intlevel;
privatelongdownT;
Stringsountime;
publicSoundTextView(Contextcontext){
super(context);
init();
}
publicSoundTextView(Contextcontext,AttributeSetattrs,intdefStyle){
super(context,attrs,defStyle);
this.mContext=context;
init();
}
publicSoundTextView(Contextcontext,AttributeSetattrs){
super(context,attrs);
this.mContext=context;
init();
}
privatevoidinit(){
recordIndicator=newDialog(getContext(),R.style.jmui_record_voice_dialog);
recordIndicator.setContentView(R.layout.jmui_dialog_record_voice);
mVoiceTime=(TextView)recordIndicator.findViewById(R.id.voice_time);
file=newFile(Environment.getExternalStorageDirectory()+"/recoder.amr");
fileto=newFile(Environment.getExternalStorageDirectory()+"/recoder.mp3");
recordManager=newRecordManager(
(Activity)mContext,
String.valueOf(file),
String.valueOf(fileto));
recordManager.setOnAudioStatusUpdateListener(newRecordManager.OnAudioStatusUpdateListener(){
@Override
publicvoidonUpdate(doubledb){
//得到分贝
if(null!=recordIndicator){
level=(int)db;
handler.sendEmptyMessage(0x111);
}
}
});
}
Handlerhandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
super.handleMessage(msg);
switch(msg.what){
case0x111:
sountime=ProgressTextUtils.getSecsProgress(System.currentTimeMillis()-downT);
longtime=System.currentTimeMillis()-downT;
mVoiceTime.setText(ProgressTextUtils.getProgressText(time));
//判断时间
judetime(Integer.parseInt(sountime));
break;
}
}
};
publicvoidjudetime(inttime){
if(time>14){
//结束录制
Toast.makeText(mContext,"录音不能超过十五秒",Toast.LENGTH_SHORT).show();
recordManager.stop_mp3();
newThread(){
@Override
publicvoidrun(){
super.run();
recordManager.saveData();
finishRecord(fileto.getPath(),sountime);
}
}.start();
recordIndicator.dismiss();
type="2";
}
}
@Override
publicbooleanonTouchEvent(MotionEventevent){
intaction=event.getAction();
switch(action){
caseMotionEvent.ACTION_DOWN:
if(type.equals("1")){
//开始发送时间
downT=System.currentTimeMillis();
recordManager.start_mp3();
recordIndicator.show();
}else{
Log.e("-log-","您已经录制完毕:");
}
returntrue;
caseMotionEvent.ACTION_UP:
if(type.equals("1")){
try{
if(Integer.parseInt(sountime)>2){
recordManager.stop_mp3();
newThread(){
@Override
publicvoidrun(){
super.run();
recordManager.saveData();
finishRecord(fileto.getPath(),sountime);
}
}.start();
if(recordIndicator.isShowing()){
recordIndicator.dismiss();
}
type="2";
}else{
recordManager.stop_mp3();
if(recordIndicator.isShowing()){
recordIndicator.dismiss();
}
sountime=null;
Toast.makeText(mContext,"录音时间少于3秒,请重新录制",Toast.LENGTH_SHORT).show();
}
}catch(Exceptione){
recordManager.stop_mp3();
if(recordIndicator.isShowing()){
recordIndicator.dismiss();
}
sountime=null;
Toast.makeText(mContext,"录音时间少于3秒,请重新录制",Toast.LENGTH_SHORT).show();
}
}
break;
caseMotionEvent.ACTION_CANCEL:
if(recordIndicator.isShowing()){
recordIndicator.dismiss();
}
break;
}
returnsuper.onTouchEvent(event);
}
//录音完毕加载ListViewitem
privatevoidfinishRecord(Stringpath,Stringtime){
if(onRecordFinishedListener!=null){
onRecordFinishedListener.newMessage(path,Integer.parseInt(time));
type="1";
}
//发送语音
//Toasts.toast(getContext(),"您已经录完了一条语音"+myRecAudioFile);
}
privateOnRecordFinishedListeneronRecordFinishedListener;
publicvoidsetOnRecordFinishedListener(OnRecordFinishedListeneronRecordFinishedListener){
this.onRecordFinishedListener=onRecordFinishedListener;
}
publicinterfaceOnRecordFinishedListener{
voidnewMessage(Stringpath,intduration);
}
}
主要的录音管理类
publicclassRecordManager{
//录制成MP3格式..............................................
/**构造时候需要的Activity,主要用于获取文件夹的路径*/
privateActivityactivity;
/**文件代号*/
publicstaticfinalintRAW=0X00000001;
publicstaticfinalintMP3=0X00000002;
/**文件路径*/
privateStringrawPath=null;
privateStringmp3Path=null;
/**采样频率*/
privatestaticfinalintSAMPLE_RATE=11025;
/**录音需要的一些变量*/
privateshort[]mBuffer;
privateAudioRecordmRecorder;
/**录音状态*/
privatebooleanisRecording=false;
/**是否转换ok*/
privatebooleanconvertOk=false;
publicRecordManager(Activityactivity,StringrawPath,Stringmp3Path){
this.activity=activity;
this.rawPath=rawPath;
this.mp3Path=mp3Path;
}
/**开始录音*/
publicbooleanstart_mp3(){
//如果正在录音,则返回
if(isRecording){
returnisRecording;
}
//初始化
if(mRecorder==null){
initRecorder();
}
getFilePath();
mRecorder.startRecording();
startBufferedWrite(newFile(rawPath));
isRecording=true;
returnisRecording;
}
/**停止录音,并且转换文件,这很可能是个耗时操作,建议在后台中做*/
publicbooleanstop_mp3(){
if(!isRecording){
returnisRecording;
}
//停止
mRecorder.stop();
isRecording=false;
//TODO
//开始转换(转换代码就这两句)
//FLameUtilslameUtils=newFLameUtils(1,SAMPLE_RATE,96);
//convertOk=lameUtils.raw2mp3(rawPath,mp3Path);
//returnisRecording^convertOk;//convertOk==true,returntrue
returnisRecording;
}
publicvoidsaveData(){
FLameUtilslameUtils=newFLameUtils(1,SAMPLE_RATE,96);
convertOk=lameUtils.raw2mp3(rawPath,mp3Path);
}
/**获取文件的路径*/
publicStringgetFilePath(intfileAlias){
if(fileAlias==RAW){
returnrawPath;
}elseif(fileAlias==MP3){
returnmp3Path;
}else
returnnull;
}
/**清理文件*/
publicvoidcleanFile(intcleanFlag){
Filef=null;
try{
switch(cleanFlag){
caseMP3:
f=newFile(mp3Path);
if(f.exists())
f.delete();
break;
caseRAW:
f=newFile(rawPath);
if(f.exists())
f.delete();
break;
caseRAW|MP3:
f=newFile(rawPath);
if(f.exists())
f.delete();
f=newFile(mp3Path);
if(f.exists())
f.delete();
break;
}
f=null;
}catch(Exceptione){
e.printStackTrace();
}
}
/**关闭,可以先调用cleanFile来清理文件*/
publicvoidclose(){
if(mRecorder!=null)
mRecorder.release();
activity=null;
}
/**初始化*/
privatevoidinitRecorder(){
intbufferSize=AudioRecord.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);
mBuffer=newshort[bufferSize];
mRecorder=newAudioRecord(MediaRecorder.AudioSource.MIC,SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,
bufferSize);
}
/**设置路径,第一个为raw文件,第二个为mp3文件*/
privatevoidgetFilePath(){
try{
Stringfolder="audio_recorder_2_mp3";
StringfileName=String.valueOf(System.currentTimeMillis());
if(rawPath==null){
Fileraw=newFile(activity.getDir(folder,
activity.MODE_PRIVATE),fileName+".raw");
raw.createNewFile();
rawPath=raw.getAbsolutePath();
raw=null;
}
if(mp3Path==null){
Filemp3=newFile(activity.getDir(folder,
activity.MODE_PRIVATE),fileName+".mp3");
mp3.createNewFile();
mp3Path=mp3.getAbsolutePath();
mp3=null;
}
Log.d("rawPath",rawPath);
Log.d("mp3Path",mp3Path);
}catch(Exceptione){
e.printStackTrace();
}
}
/**执行cmd命令,并等待结果*/
privatebooleanrunCommand(Stringcommand){
booleanret=false;
Processprocess=null;
try{
process=Runtime.getRuntime().exec(command);
process.waitFor();
ret=true;
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
process.destroy();
}catch(Exceptione){
e.printStackTrace();
}
}
returnret;
}
/**写入到raw文件*/
privatevoidstartBufferedWrite(finalFilefile){
ObjectmLock=newObject();
newThread(newRunnable(){
@Override
publicvoidrun(){
DataOutputStreamoutput=null;
try{
output=newDataOutputStream(newBufferedOutputStream(
newFileOutputStream(file)));
while(isRecording){//开始录制
intreadSize=mRecorder.read(mBuffer,0,
mBuffer.length);//是实际读取的数据长度
for(inti=0;i
完整代码:http://xiazai.jb51.net/201911/yuanma/AudioDemo_jb51.rar
总结
以上所述是小编给大家介绍的Android仿微信录音功能(录音后的raw文件转mp3文件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。