一、简述
效果:
实现功能:
长按button时改变button显示文字,d出Dialog(动态更新音量),动态生成录音文件,开始录音;
监听手指动作,规定区域。录音状态下手指划出规定区域取消录音,删除生成的录音文件;
监听手指动作。当手指抬起时,判断是否开始录音,录音时长是否过短,符合条件则提示录音时长过短;正常结束时通过回调返回该次录音的文件路径和时长。
4.点击录音列表的item时,播放动画,播放对应的音频文件。
主要用到4个核心类:
自定义录音按钮(AudioRecordbutton);
d框管理类(DialogManager);
录音管理类(AudioManager)。
1.AudioRecordbutton状态:
1.STATE_norMAL:普通状态
2.STATE_RECORDING:录音中
3.STATE_CANCEL:取消录音
2.DialogManager状态:
1.RECORDING:录音中
2.WANT_TO_CANCEL:取消录音
3.TOO_SHORT:录音时间太短
3.AudioManager:
1.prepare():准备状态
2.cancel():取消录音
3.release():正常结束录音
4.getVoiceLevel():获取音量
核心逻辑:
自定义button,重写ontouchEvent()方法。
伪代码:
class AudioRecorderbutton{ ontouchEvent(){ DOWN: changebuttonState(STATE_RECORDING); | DialogManager.showDialog(RECORDING) 触发LongClick事件(AudioManager.prepare() --> end prepared --> | ); | getVoiceLevel();//开启一个线程,更新Dialog上的音量等级 MOVE: if(wantCancel(x,y)){ DialogManager.showDialog(WANT_TO_CANCEL);更新Dialog changebuttonState(STATE_WANT_TO_CANCEL);更新button状态 }else{ DialogManager.showDialog(WANT_TO_CANCEL); changebuttonState(STATE_RECORDING); } UP: if(wantCancel == curState){//当前状态是想取消状态 AudioManager.cancel(); } if(STATE_RECORDING = curState){ if(tooShort){//判断录制时长,如果录制时间过短 DialogManager.showDialog(TOO_SHORT); } AudioManager.release(); callbackActivity(url,time);//(当前录音文件路径,时长) } }}
二、MediaManager封装
简述:使用MediaPlayer播放录制好的音频文件,要注意MediaPlayer资源的释放。
代码:
import androID.media.*;import java.io.IOException;/** * 播放管理类 */public class MediaManager { private static MediaPlayer mMediaPlayer; private static boolean isPause; public static voID playSound(String filePath,MediaPlayer.OnCompletionListener onCompletionListener) { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setonErrorListener(new MediaPlayer.OnErrorListener() { @OverrIDe public boolean onError(MediaPlayer mp,int what,int extra) { mMediaPlayer.reset(); return false; } }); } else { mMediaPlayer.reset(); } try { mMediaPlayer.setAudioStreamType(androID.media.AudioManager.STREAM_MUSIC); mMediaPlayer.setonCompletionListener(onCompletionListener); mMediaPlayer.setDataSource(filePath); mMediaPlayer.prepare(); mMediaPlayer.start(); } catch (IOException e) { e.printstacktrace(); } } public static voID pause(){ if(mMediaPlayer != null && mMediaPlayer.isPlaying()){ mMediaPlayer.pause(); isPause = true; } } public static voID resume(){ if(mMediaPlayer != null && isPause){ mMediaPlayer.start(); isPause = false; } } public static voID release(){ if(mMediaPlayer != null){ mMediaPlayer.release(); mMediaPlayer = null; } }}
三、DialogManager封装
封装了6个方法:
1. showRecordingDialog():用来设置Diaog布局,拿到控件的引用,显示Dialog。
2. recording():更改Dialog状态为录音中状态。
3. wantToCancel():更改Dialog状态为想要取消状态。
4. tooShort():更改Dialog状态为录音时长过短状态。
5. dismissDialog():移除Dialog。
6. updateVoiceLevel():用来更新音量图片。
代码:
import androID.app.Dialog;import androID.content.Context;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.Widget.ImageVIEw;import androID.Widget.TextVIEw;import com.tIDdlerliu.wxrecorder.R;/** * Dialog管理类 */public class DialogManager { private Dialog mDialog; private ImageVIEw mIcon; private ImageVIEw mVoice; private TextVIEw mLabel; private Context mContext; public DialogManager(Context context) { mContext = context; } /** * 显示Dialog */ public voID showRecordingDialog(){ //将布局应用于Dialog mDialog = new Dialog(mContext,R.style.theme_AudioDialog); LayoutInflater inflater = LayoutInflater.from(mContext); VIEw vIEw = inflater.inflate(R.layout.dialog_recorder,null); mDialog.setContentVIEw(vIEw); //成员控件赋值 mIcon = (ImageVIEw) mDialog.findVIEwByID(R.ID.recorder_dialog_icon); mVoice = (ImageVIEw) mDialog.findVIEwByID(R.ID.recorder_dialog_voice); mLabel = (TextVIEw) mDialog.findVIEwByID(R.ID.recorder_dialog_label); mDialog.show(); } public voID recording(){ if(mDialog != null && mDialog.isShowing()){ mIcon.setVisibility(VIEw.VISIBLE); mVoice.setVisibility(VIEw.VISIBLE); mLabel.setVisibility(VIEw.VISIBLE); mIcon.setimageResource(R.mipmap.recorder); mLabel.setText("手指上滑,取消发送"); } } public voID wantToCancel(){ if(mDialog != null && mDialog.isShowing()){ mIcon.setVisibility(VIEw.VISIBLE); mVoice.setVisibility(VIEw.GONE); mLabel.setVisibility(VIEw.VISIBLE); mIcon.setimageResource(R.mipmap.cancel); mLabel.setText("松开手指,取消发送"); } } public voID tooShort(){ if(mDialog != null && mDialog.isShowing()){ mIcon.setVisibility(VIEw.VISIBLE); mVoice.setVisibility(VIEw.GONE); mLabel.setVisibility(VIEw.VISIBLE); mIcon.setimageResource(R.mipmap.voice_to_short); mLabel.setText("录音时间过短"); } } public voID dismissDialog(){ if(mDialog != null && mDialog.isShowing()){ mDialog.dismiss(); mDialog = null; } } /** * 通过level更新音量资源图片 * @param level */ public voID updateVoiceLevel(int level){ if(mDialog != null && mDialog.isShowing()){ int resID = mContext.getResources().getIDentifIEr("v"+level,"mipmap",mContext.getPackagename()); mVoice.setimageResource(resID); } }}
四、AudioManager封装
4.1 添加必要权限
<uses-permission androID:name="androID.permission.RECORD_AUdio"/><uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/>
4.2 代码
import androID.media.MediaRecorder;import java.io.file;import java.io.IOException;import java.util.UUID;/** * 录音管理类 */public class AudioManager { private String mDir;//文件夹名称 private MediaRecorder mMediaRecorder; private String mCurrentfilePath;//文件储存路径 private static AudioManager mInstance; //表明MediaRecorder是否进入prepare状态(状态为true才能调用stop和release方法) private boolean isPrepared; public AudioManager(String dir) { mDir = dir; } public String getCurrentfilePath() { return mCurrentfilePath; } /** * 准备完毕接口 */ public interface AudioStateListener{ voID wellPrepared(); } public AudioStateListener mListener; public voID setonAudioStateListener(AudioStateListener Listener){ mListener = Listener; } /** * 单例 * @return AudioManager */ public static AudioManager getInstance(String dir){ if (mInstance == null){ synchronized (AudioManager.class){ if(mInstance == null){ mInstance = new AudioManager(dir); } } } return mInstance; } /** * 准备 */ public voID prepareAudio() { try { isPrepared = false; file dir = new file(mDir);//创建文件夹 if (!dir.exists()) { dir.mkdirs(); } String filename = generatefilename();//随机生成文件名 file file = new file(dir,filename);//创建文件 mCurrentfilePath = file.getabsolutePath(); mMediaRecorder = new MediaRecorder(); mMediaRecorder.setoutputfile(file.getabsolutePath());//设置输出文件 mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置麦克风为音频源 mMediaRecorder.setoutputFormat(MediaRecorder.OutputFormat.AMR_NB);//设置音频格式 mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//设置音频编码 mMediaRecorder.prepare(); mMediaRecorder.start(); //准备结束 isPrepared = true; if (mListener != null){ mListener.wellPrepared(); } } catch (IOException e) { e.printstacktrace(); } } /** * 随机生成文件的名称 * @return */ private String generatefilename() { return UUID.randomUUID().toString()+".amr"; } /** * 获取音量等级 */ public int getVoiceLevel(int maxLevel) { if (isPrepared) { try { //mMediaRecorder.getMaxAmplitude() 范围:1-32767 return maxLevel * mMediaRecorder.getMaxAmplitude() / 32768 + 1;//最大值 * [0,1)+ 1 } catch (Exception e) { } } return 1; } /** * 重置 */ public voID release(){ if(mMediaRecorder != null){ mMediaRecorder.stop(); mMediaRecorder.release(); mMediaRecorder = null; } } /** * 取消 */ public voID cancel(){ release(); //删除产生的文件 if(mCurrentfilePath != null){ file file = new file(mCurrentfilePath); file.delete(); mCurrentfilePath = null; } }}
五、AudioRecordbutton封装
import androID.annotation.Suppresslint;import androID.content.Context;import androID.os.Environment;import androID.os.Handler;import androID.os.Message;import androID.util.AttributeSet;import androID.vIEw.MotionEvent;import androID.vIEw.VIEw;import androID.Widget.button;import com.tIDdlerliu.wxrecorder.R;/** * 自定义button */@Suppresslint("AppCompatCustomVIEw")public class AudioRecordbutton extends button implements AudioManager.AudioStateListener{ private static final int STATE_norMAL = 1;//默认状态 private static final int STATE_RECORDING = 2;//录音状态 private static final int STATE_WANT_CANCEL = 3;//想取消状态 private static final int disTANCE_Y_CANCEL = 50;//定义上滑取消距离 private int mCurState = STATE_norMAL;//记录当前状态 private boolean isRecording = false;//是否在录音状态 private DialogManager mDialogManager; private AudioManager mAudioManager; private float mTime;//记录录音时长 private boolean mReady;//是否触发OnLongClick事件 private boolean isComplete = true;//是否已经完成 public AudioRecordbutton(Context context) { this(context,null); } public AudioRecordbutton(Context context,AttributeSet attrs) { super(context,attrs); mDialogManager = new DialogManager(getContext()); String dir = Environment.getExternalStorageDirectory()+"/TIDdlerliu/recorder/audios";//最好判断SD卡是否存在可读 mAudioManager = AudioManager.getInstance(dir); mAudioManager.setonAudioStateListener(this); setonLongClickListener(new OnLongClickListener() { @OverrIDe public boolean onLongClick(VIEw v) { mReady = true; mAudioManager.prepareAudio(); return false; } }); } /** * 录音完成后的回调 */ public interface AudioFinishRecorderListener { voID onFinish(float seconds,String filePath); } private AudioFinishRecorderListener mAudioFinishRecorderListener; public voID setAudioFinishRecorderListener(AudioFinishRecorderListener Listener){ mAudioFinishRecorderListener = Listener; } private static final int MSG_AUdio_PREPARED = 0x110; private static final int MSG_VOICE_CHANGED = 0x111; private static final int MSG_DIALOG_disMISS = 0x112; private static final int MSG_AUdio_COMPLETE = 0x113;//达到最大时长,自动完成 /** * 获取音量大小 */ private Runnable mGetVoiceLevelRunnable = new Runnable() { @OverrIDe public voID run() { while (isRecording){ try { Thread.sleep(100); mTime += 0.1f; if(mTime >= 60f){//60s自动触发完成录制 mHandler.sendEmptyMessage(MSG_AUdio_COMPLETE); } mHandler.sendEmptyMessage(MSG_VOICE_CHANGED); } catch (InterruptedException e) { e.printstacktrace(); } } } }; private Handler mHandler = new Handler(){ @OverrIDe public voID handleMessage(Message msg) { switch (msg.what){ case MSG_AUdio_PREPARED: //显示应该在audio end prepared以后 mDialogManager.showRecordingDialog(); isRecording = true; isComplete = false; new Thread(mGetVoiceLevelRunnable).start(); break; case MSG_VOICE_CHANGED: mDialogManager.updateVoiceLevel(mAudioManager.getVoiceLevel(7)); break; case MSG_DIALOG_disMISS: mDialogManager.dismissDialog(); break; case MSG_AUdio_COMPLETE: complete(); reset(); break; default: break; } } }; @OverrIDe public voID wellPrepared() { mHandler.sendEmptyMessage(MSG_AUdio_PREPARED); } @OverrIDe public boolean ontouchEvent(MotionEvent event) { int action = event.getAction(); int x = (int) event.getX(); int y = (int) event.getY(); switch (action){ case MotionEvent.ACTION_DOWN: changeState(STATE_RECORDING); break; case MotionEvent.ACTION_MOVE: if(isRecording){ //根据(x,y)坐标,判断是否想要取消 if (wantToCancel(x,y)){ changeState(STATE_WANT_CANCEL); }else{ changeState(STATE_RECORDING); } } break; case MotionEvent.ACTION_UP: if(!isComplete){//没有执行超时自动完成逻辑 if (!mReady) {//还未触发OnLongClick事件 reset(); return super.ontouchEvent(event); } if (!isRecording || mTime < 0.6f) {//还未开始录音 或者 录制时长过短 mDialogManager.tooShort(); mAudioManager.cancel(); mHandler.sendEmptyMessageDelayed(MSG_DIALOG_disMISS,1300);//1.3秒后关闭对话框 } else if (mCurState == STATE_RECORDING) {//正常录制结束 complete(); } else if (mCurState == STATE_WANT_CANCEL) {//想要取消状态 mDialogManager.dismissDialog(); mAudioManager.cancel(); } reset(); } break; } return super.ontouchEvent(event); } /** * 正常录制结束 */ private voID complete() { mDialogManager.dismissDialog(); mAudioManager.release(); if(mAudioFinishRecorderListener != null && !isComplete){ mAudioFinishRecorderListener.onFinish(mTime,mAudioManager.getCurrentfilePath()); } } /** * 恢复状态和标志位 */ private voID reset() { isRecording = false; mReady = false; mTime = 0; isComplete = true; changeState(STATE_norMAL); } /** * 根据(x,y)坐标,判断是否想要取消 * @param x * @param y * @return */ private boolean wantToCancel(int x,int y) { if(x < 0 || x > getWIDth()){//手指移出button范围 return true; } if(y < - disTANCE_Y_CANCEL || y > getHeight() + disTANCE_Y_CANCEL){//手指移出Y轴设定范围 return true; } return false; } /** * 改变状态 * @param state */ private voID changeState(int state) { if(mCurState != state){ mCurState = state; switch (state){ case STATE_norMAL: setBackgroundResource(R.drawable.btn_recorder_normal); setText(R.string.str_recorder_normal); break; case STATE_RECORDING: setBackgroundResource(R.drawable.btn_recorder_recording); setText(R.string.str_recorder_recording); if(isRecording){ mDialogManager.recording(); } break; case STATE_WANT_CANCEL: setBackgroundResource(R.drawable.btn_recorder_recording); setText(R.string.str_recorder_want_cancel); mDialogManager.wantToCancel(); break; default: break; } } }}
六、 主界面实现
6.1 adapter
import androID.content.Context;import androID.support.annotation.NonNull;import androID.support.annotation.Nullable;import androID.util.displayMetrics;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;import androID.vIEw.WindowManager;import androID.Widget.ArrayAdapter;import androID.Widget.TextVIEw;import com.tIDdlerliu.wxrecorder.R;import com.tIDdlerliu.wxrecorder.model.Recorder;import java.util.List;public class RecorderAdapter extends ArrayAdapter<Recorder>{ private int mMinItemWIDth; private int mMaxItemWIDth; private LayoutInflater mInflater; public RecorderAdapter(@NonNull Context context,List<Recorder> datas) { super(context,-1,datas); mInflater = LayoutInflater.from(context); //获取屏幕参数 WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); displayMetrics outMetrics = new displayMetrics(); wm.getDefaultdisplay().getMetrics(outMetrics); //设置最小宽度和最大宽度 mMinItemWIDth = (int) (outMetrics.wIDthPixels * 0.16f); mMaxItemWIDth = (int) (outMetrics.wIDthPixels * 0.64f); } @NonNull @OverrIDe public VIEw getVIEw(int position,@Nullable VIEw convertVIEw,@NonNull VIEwGroup parent) { VIEwHolder holder = null; if(convertVIEw == null){ convertVIEw = mInflater.inflate(R.layout.item_recorder,parent,false); holder = new VIEwHolder(); holder.seconds = (TextVIEw) convertVIEw.findVIEwByID(R.ID.item_recorder_time); holder.length = convertVIEw.findVIEwByID(R.ID.item_recorder_length); convertVIEw.setTag(holder); }else { holder = (VIEwHolder) convertVIEw.getTag(); } //设置时长 holder.seconds.setText(Math.round(getItem(position).getTime())+ "\""); //根据时长按比例设置时长 VIEwGroup.LayoutParams lp = holder.length.getLayoutParams(); lp.wIDth = (int) (mMinItemWIDth + (mMaxItemWIDth/60f * getItem(position).getTime())); return convertVIEw; } private class VIEwHolder{ TextVIEw seconds; VIEw length; }}
6.2 activity
import androID.graphics.drawable.AnimationDrawable;import androID.media.MediaPlayer;import androID.os.Bundle;import androID.support.v7.app.AppCompatActivity;import androID.vIEw.VIEw;import androID.Widget.AdapterVIEw;import androID.Widget.ArrayAdapter;import androID.Widget.ListVIEw;import com.tIDdlerliu.wxrecorder.CustomVIEw.AudioRecordbutton;import com.tIDdlerliu.wxrecorder.CustomVIEw.MediaManager;import com.tIDdlerliu.wxrecorder.adapter.RecorderAdapter;import com.tIDdlerliu.wxrecorder.model.Recorder;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity { private ListVIEw mListVIEw; private AudioRecordbutton mAudioRecordbutton; private ArrayAdapter<Recorder> mAdapter ; private List<Recorder> mDatas = new ArrayList<>(); private VIEw mAnimVIEw; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); mListVIEw = (ListVIEw) findVIEwByID(R.ID.recorder_List); mAudioRecordbutton = (AudioRecordbutton) findVIEwByID(R.ID.recorder_button); mAudioRecordbutton.setAudioFinishRecorderListener(new AudioRecordbutton.AudioFinishRecorderListener() { @OverrIDe public voID onFinish(float seconds,String filePath) { Recorder recorder = new Recorder(seconds,filePath); mDatas.add(recorder); mAdapter.notifyDataSetChanged(); mListVIEw.setSelection(mDatas.size()-1); } }); mAdapter = new RecorderAdapter(this,mDatas); mListVIEw.setAdapter(mAdapter); mListVIEw.setonItemClickListener(new AdapterVIEw.OnItemClickListener() { @OverrIDe public voID onItemClick(AdapterVIEw<?> parent,VIEw vIEw,int position,long ID) { if(mAnimVIEw != null){ mAnimVIEw.setBackgroundResource(R.mipmap.adj); mAnimVIEw = null; } //播放动画 mAnimVIEw = vIEw.findVIEwByID(R.ID.item_recorder_anim); mAnimVIEw.setBackgroundResource(R.drawable.play_ainm); AnimationDrawable anim = (AnimationDrawable) mAnimVIEw.getBackground(); anim.start(); //播放音频 MediaManager.playSound(mDatas.get(position).getfilePath(),new MediaPlayer.OnCompletionListener() { @OverrIDe public voID onCompletion(MediaPlayer mp) { mAnimVIEw.setBackgroundResource(R.mipmap.adj); } }); } }); } @OverrIDe protected voID onPause() { super.onPause(); MediaManager.pause(); } @OverrIDe protected voID onResume() { super.onResume(); MediaManager.resume(); } @OverrIDe protected voID onDestroy() { super.onDestroy(); MediaManager.release(); }}
总结
以上所述是小编给大家介绍的AndroID仿微信语音消息的录制和播放功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!
总结以上是内存溢出为你收集整理的Android仿微信语音消息的录制和播放功能全部内容,希望文章能够帮你解决Android仿微信语音消息的录制和播放功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)