Android仿微信、录制音频并发送功能

Android仿微信、录制音频并发送功能,第1张

概述MyRecorder(仿微信,录制音频发送功能)①布局实现(activity_main.xml)布局采用线性布局,上面使用的一个ListView,下面使用的是一个自定义的Button(会在下面进行介绍)

MyRecorder(仿微信,录制音频并发送功能)

①布局实现(activity_main.xml)
布局采用线性布局,上面使用的一个ListVIEw,下面使用的是一个自定义的button(会在下面进行介绍)

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" tools:context="com.yitong.myrecorder.MainActivity"> <ListVIEw  androID:ID="@+ID/main_ListvIEw"  androID:layout_wIDth="match_parent"  androID:layout_height="0dp"  androID:layout_weight="1"  androID:background="#ebebeb"  androID:divIDerHeight="10dp"  androID:divIDer="@null"  /> <FrameLayout  androID:layout_wIDth="match_parent"  androID:layout_height="wrap_content"  androID:background="#fff">  <com.yitong.myrecorder.vIEw.AudioRecorderbutton   androID:ID="@+ID/main_btn"   androID:layout_wIDth="match_parent"   androID:layout_height="wrap_content"   androID:gravity="center"   androID:layout_margintop="6dp"   androID:layout_marginBottom="6dp"   androID:layout_marginleft="60dp"   androID:layout_marginRight="60dp"   androID:minHeight="0dp"   androID:padding="6dp"   androID:text="@string/str_recoder_normal"   androID:textSize="20sp"   androID:textcolor="#727272"   androID:background="@drawable/btn_recorder_normal"   />  <VIEw   androID:layout_wIDth="match_parent"   androID:layout_height="1dp"   androID:background="#ccc"/> </FrameLayout></linearLayout>

相关使用的string值(需要添加到value/string中):  

 <string name="str_recoder_normal">按住说话</string> <string name="str_recorder_recording">松开结束</string> <string name="str_recorder_want_cancel">松开手指,取消发送</string> <string name="str_dialog_want_cancel">手指上滑,取消发送</string> <string name="str_dialog_want_send">手指上滑,取消发送</string> <string name="str_dialog_time_short">录音时间过短</string>

②我们分析一下自定button的几种状态:
1.正常状态 (在初次显示,即没有点击的时候显示的状态,显示的文本为“按住说话”)
2.录音状态 (当手指按在button上时,即为录音状态,显示的文本为“松开结束”)
3.取消状态 (当手指上滑,此时若松开手指,便取消发送,即为取消状态,显示的文本为“松开手指,取消发送”)

③当录音状态时,在VIEw上有一个Dialog的提示,首先我们先自定义这个Dialog的布局:

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:background="@drawable/dialog_bg"    androID:orIEntation="vertical"    androID:padding="20dp"> <linearLayout  androID:layout_wIDth="wrap_content"  androID:layout_height="wrap_content"  androID:layout_gravity="center_horizontal"  androID:orIEntation="horizontal">  <ImageVIEw   androID:ID="@+ID/main_recorder_dialog_icon"   androID:layout_wIDth="wrap_content"   androID:layout_height="wrap_content"   androID:src="@mipmap/recorder"   androID:visibility="visible"/>  <ImageVIEw   androID:ID="@+ID/main_recorder_dialog_voice"   androID:layout_wIDth="wrap_content"   androID:layout_height="wrap_content"   androID:src="@mipmap/v1"   androID:visibility="visible"/> </linearLayout> <TextVIEw  androID:ID="@+ID/main_recorder_dialog_label"  androID:layout_wIDth="wrap_content"  androID:layout_height="wrap_content"  androID:layout_gravity="center_horizontal"  androID:layout_margintop="5dp"  androID:text="@string/str_dialog_want_cancel"  androID:textcolor="#fff"  androID:textSize="20sp"/></linearLayout>

其中用到的@drawable/dialog_bg即为自定的shape

 <?xml version="1.0" enCoding="utf-8"?> <shape xmlns:androID="http://schemas.androID.com/apk/res/androID"   androID:shape="rectangle">  <corners androID:radius="12dp"/>  <solID androID:color="#a3d7f5"/>  <stroke   androID:wIDth="1dp"   androID:color="#9b9b9b"/> </shape>

④定义DialogManager,便于对这个自定义布局的Dialog进行 *** 作

public class DialogManager { private static final String TAG = "DialogManager"; private Dialog mDialog; private ImageVIEw mIcon; private ImageVIEw mVoice; private TextVIEw mLabel; private Context mContext; public DialogManager(Context mContext) {  this.mContext = mContext; } /**  * 显示对话框  */ public voID showRecordeingDialog() {  mDialog = new Dialog(mContext,R.style.theme_AudioDialog);  LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);  VIEw vIEw = inflater.inflate(R.layout.dialog,null);  mDialog.setContentVIEw(vIEw);  mIcon = (ImageVIEw) mDialog.findVIEwByID(R.ID.main_recorder_dialog_icon);  mVoice = (ImageVIEw) mDialog.findVIEwByID(R.ID.main_recorder_dialog_voice);  mLabel = (TextVIEw) mDialog.findVIEwByID(R.ID.main_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(R.string.str_dialog_want_send);  } } /**  * 取消录制对话框提示  */ public voID wantToCancel() {  if (mDialog != null && mDialog.isShowing()) {   mIcon.setVisibility(VIEw.VISIBLE);   mVoice.setVisibility(VIEw.VISIBLE);   mLabel.setVisibility(VIEw.VISIBLE);   mIcon.setimageResource(R.mipmap.recorder);   mLabel.setText(R.string.str_recorder_want_cancel);  } } /**  * 录音时间过短提示  */ public voID tooShort() {  if (mDialog != null && mDialog.isShowing()) {   mIcon.setVisibility(VIEw.VISIBLE);   mVoice.setVisibility(VIEw.VISIBLE);   mLabel.setVisibility(VIEw.VISIBLE);   mIcon.setimageResource(R.mipmap.recorder);   mLabel.setText(R.string.str_dialog_time_short);  } } /**  * 取消对话框  */ public voID dismissDialog() {  if (mDialog != null && mDialog.isShowing()) {   mDialog.dismiss();   mDialog = null;  } } /**  * 显示音量大小  */ public voID updateVoiceLevel(int level) {  if (mDialog != null && mDialog.isShowing()) {   int resID = mContext.getResources().getIDentifIEr("v" + level,"mipmap",mContext.getPackagename());   mVoice.setimageResource(resID);  } }}

Dialog的样式theme_AudioDialog,需要在values/styles.xml中定义

 <style name="theme_AudioDialog">  <item name="androID:windowBackground">@androID:color/transparent</item>  <item name="androID:windowFrame">@null</item>  <item name="androID:windowIsfloating">true</item>  <item name="androID:windowIsTranslucent">true</item>  <item name="androID:backgroundDimEnabled">false</item> </style>

⑤当手指按住button时,便开始录音,所以我们还需要定义一个录音的管理类AudioManager来控制录制状态。

public class AudioManager { private MediaRecorder mMediaRecorder; private String mDir;// 保存的目录 private String mCurrentfilePath;// 保存音频文件的全路径 private boolean isPrepared = false;// 是否准备完毕 private AudioManager(String dir) {  mDir = dir; } private static AudioManager mInstance; public static AudioManager getmInstance(String mDir) {  if (mInstance == null) {   synchronized (AudioManager.class) {    if (mInstance == null) {     mInstance = new AudioManager(mDir);    }   }  }  return mInstance; } /**  * 准备完毕的回调  */ public interface AudioStateListener {  voID wellPrepared(); } private AudioStateListener mListener; public voID setAudioStateListener(AudioStateListener Listener) {  mListener = Listener; } /** 准备录制 */ public voID prepareAudio() {  try {   isPrepared = false;   file dir = new file(mDir);   if (!dir.exists()) {    dir.mkdirs();   }   String filename = generatename();   file file = new file(dir,filename);   mCurrentfilePath = file.getabsolutePath();   mMediaRecorder = new MediaRecorder();   // 设置输出文件   mMediaRecorder.setoutputfile(mCurrentfilePath);   // 设置音频源为麦克风   mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);   // 设置音频格式   mMediaRecorder.setoutputFormat(MediaRecorder.OutputFormat.RAW_AMR);   // 设置音频编码   mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);   mMediaRecorder.prepare();   mMediaRecorder.start();   isPrepared = true;   if (mListener != null) {    mListener.wellPrepared();   }  } catch (Exception e) {   e.printstacktrace();  } } /** 获取音量大小 */ public int getVoiceLevel(int maxLevel) {  if (isPrepared) {   try {    //mMediaRecorder.getMaxAmplitude() 1-32767    //注意此处mMediaRecorder.getMaxAmplitude 只能取一次,如果前面取了一次,后边再取就为0了    return ((mMediaRecorder.getMaxAmplitude() * maxLevel) / 32768) + 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);   if(file.exists()) {    file.delete();    mCurrentfilePath = null;   }  } } /** 获取录制音频的总路径 */ public String getmCurrentfilePath(){  return mCurrentfilePath; } /**  * 生成一个随机名字  */ private String generatename() {  return UUID.randomUUID().toString() + ".mp3"; }}

⑥处理完DialogManager和Audiomanger后,接着我们回到自定义的button,即AudioRecorderbutton

public class AudioRecorderbutton 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_TO_CANCEL = 3;//取消状态 private static final String TAG = "AudioRecorderbutton"; private int mCurState = STATE_norMAL;//当前状态 private boolean isRecording = false;//是否正在录音 private DialogManager mDialogmanger; private AudioManager mAudioManager; private boolean mReady = false;//是否触发longClick private float mTime;//计时 public AudioRecorderbutton(Context context) {  this(context,null); } public AudioRecorderbutton(Context context,AttributeSet attrs) {  this(context,attrs,0); } public AudioRecorderbutton(Context context,AttributeSet attrs,int defStyleAttr) {  super(context,defStyleAttr);  mDialogmanger = new DialogManager(getContext());  String dir = Environment.getExternalStorageDirectory() + "/my_recorder_audios";  mAudioManager = AudioManager.getmInstance(dir);  mAudioManager.setAudioStateListener(this);  setonLongClickListener(new OnLongClickListener() {   @OverrIDe   public boolean onLongClick(VIEw v) {    mReady = true;    mAudioManager.prepareAudio();    return false;   }  }); } @OverrIDe public boolean ontouchEvent(MotionEvent event) {  int x = (int) event.getX();  int y = (int) event.getY();  switch (event.getAction()) {   case MotionEvent.ACTION_DOWN:    changeSate(STATE_RECORDING);    break;   case MotionEvent.ACTION_MOVE:    if (isRecording) {     if (isCancelRecorder(x,y)) {      changeSate(STATE_WANT_TO_CANCEL);     } else {      changeSate(STATE_RECORDING);     }    }    break;   case MotionEvent.ACTION_UP:    if (!mReady) {     reset();     return super.ontouchEvent(event);    }    if (!isRecording || mTime < 0.6f) {     mDialogmanger.tooShort();     mAudioManager.cancel();     mHandler.sendEmptyMessageDelayed(MSG_LODING_disMISS,1000);    } else if (mCurState == STATE_RECORDING) {//正常录制结束     mDialogmanger.dismissDialog();     mAudioManager.release();     if (mListener != null) {      mListener.onFinish(mTime,mAudioManager.getmCurrentfilePath());     }    } else if (mCurState == STATE_WANT_TO_CANCEL) {     mDialogmanger.dismissDialog();     mAudioManager.cancel();    }    reset();    break;  }  return super.ontouchEvent(event); } /**  * 根据不同状态,更改不同的文字和显示的背景  */ private voID changeSate(int stateRecording) {  if (mCurState != stateRecording) {   mCurState = stateRecording;   switch (mCurState) {    case STATE_norMAL:     setBackgroundResource(R.drawable.btn_recorder_normal);     setText(R.string.str_recoder_normal);     break;    case STATE_RECORDING:     setBackgroundResource(R.drawable.btn_recording);     setText(R.string.str_recorder_recording);     if (isRecording) {      mDialogmanger.recording();     }     break;    case STATE_WANT_TO_CANCEL:     setBackgroundResource(R.drawable.btn_recording);     setText(R.string.str_recorder_want_cancel);     mDialogmanger.wantToCancel();     break;   }  } } /**  * 根据移动后的位置,判断是否取消录音  */ private boolean isCancelRecorder(int x,int y) {  if (x < 0 || x > getWIDth() || y < 0 || y > getHeight()) {   return true;  }  return false; } /**  * 重置标识位  */ private voID reset() {  changeSate(STATE_norMAL);  isRecording = false;  mReady = false;  mTime = 0; } /**  * 开始播放时回调此方法  */ @OverrIDe public voID wellPrepared() {  mHandler.sendEmptyMessage(MSG_AUdio_PREPARED); } private static final int MSG_AUdio_PREPARED = 0x110; private static final int MSG_VOICE_CHAGE = 0x111; private static final int MSG_LODING_disMISS = 0x112; private Handler mHandler = new Handler() {  @OverrIDe  public voID handleMessage(Message msg) {   super.handleMessage(msg);   switch (msg.what) {    case MSG_AUdio_PREPARED:     mDialogmanger.showRecordeingDialog();     isRecording = true;     new Thread(mGetVoiceLevelRunnable).start();     break;    case MSG_VOICE_CHAGE:     mDialogmanger.updateVoiceLevel(mAudioManager.getVoiceLevel(7));     break;    case MSG_LODING_disMISS:     mDialogmanger.dismissDialog();     break;   }  } }; /**  * 获取音量大小,并计时  */ private Runnable mGetVoiceLevelRunnable = new Runnable() {  @OverrIDe  public voID run() {   while (isRecording) {    SystemClock.sleep(100);    mTime += 0.1f;    mHandler.sendEmptyMessage(MSG_VOICE_CHAGE);   }  } }; /**  * 完成录制后的回调接口  */ public interface AudioFinishRecorderListener {  voID onFinish(float time,String filePath); } private AudioFinishRecorderListener mListener; public voID setAudioFinishRecorderListener(AudioFinishRecorderListener Listener) {  mListener = Listener; }}

=====================至此自定义button就定义完===================================

①接着我们回到了MainActivity,我们需要获取ListVIEw和AudioRecorderbutton组件。对于ListVIEw,需要定义Adapter,当点击某个条目的需要把录制的音频播放出来,需要定义一个MediaManager来控制音频的播放。

②首先我们先定义RecorderAdapter

/** * 音频实体类,包含音频的长度和保存的路径 */public class Recorder implements Serializable { private int time; private String filePath; public Recorder() { } public Recorder(int time,String filePath) {  this.time = time;  this.filePath = filePath; } public voID setTime(int time) {  this.time = time; } public voID setfilePath(String filePath) {  this.filePath = filePath; } public float getTime() {  return time; } public String getfilePath() {  return filePath; }}/** * 继承ArrayAdater,重写getVIEw方法 */public class RecorderAdapter extends ArrayAdapter<Recorder> { private List<Recorder> mDatas; private Context mContext; private LayoutInflater mInfalter; private int mMinItemWIDhth; private int mMaxItemWIDhth; public RecorderAdapter(Context context,List<Recorder> datas) {  super(context,-1,datas);  mDatas = datas;  mContext = context;  mInfalter = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);  displayMetrics outMetrics = new displayMetrics();  wm.getDefaultdisplay().getMetrics(outMetrics);  mMaxItemWIDhth = (int) (outMetrics.wIDthPixels * 0.7f);  mMinItemWIDhth = (int) (outMetrics.wIDthPixels * 0.15f); } @OverrIDe public VIEw getVIEw(int position,VIEw convertVIEw,VIEwGroup parent) {  VIEwHolder holder = new VIEwHolder();  if(convertVIEw == null) {   convertVIEw = mInfalter.inflate(R.layout.item_recorder,null);  }  holder = holder.getHolder(convertVIEw);  holder.setVIEw(holder,mDatas.get(position));  return convertVIEw; } private class VIEwHolder{  TextVIEw time;  VIEw length;  public VIEwHolder getHolder(VIEw vIEw){   VIEwHolder holder = (VIEwHolder) vIEw.getTag();   if(holder == null) {    holder = new VIEwHolder();   }   holder.time = (TextVIEw) vIEw.findVIEwByID(R.ID.item_recorder_time);   holder.length = vIEw.findVIEwByID(R.ID.item_recorder_length);   vIEw.setTag(holder);   return holder;  }  public voID setVIEw(VIEwHolder holder,Recorder recorder) {   holder.time.setText(recorder.getTime() + "\"");   VIEwGroup.LayoutParams layoutParams = holder.length.getLayoutParams();   layoutParams.wIDth = (int) (mMinItemWIDhth + (mMaxItemWIDhth / 60f * recorder.getTime()));  } }}

③定义Mediamanger,用于播放音频

public class MediaManager { private static MediaPlayer mMediaPlayer; private static boolean isPause = false;//是否是暂停 /**  * 播放音频  */ 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(AudioManager.STREAM_MUSIC);   mMediaPlayer.setonCompletionListener(onCompletionListener);   mMediaPlayer.setDataSource(filePath);   mMediaPlayer.prepare();   mMediaPlayer.start();  } catch (Exception 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;  } }}

④MainActivity的实现

public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private List<Recorder> mDatas = new ArrayList<Recorder>(); private AudioRecorderbutton mAudioRecorderbutton; private ListVIEw mListVIEw; private RecorderAdapter mAdapter; private VIEw mAnimVIEw; @OverrIDe protected voID onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentVIEw(R.layout.activity_main);  initVIEw();  initaction(); } private voID initVIEw() {  mAudioRecorderbutton = (AudioRecorderbutton) findVIEwByID(R.ID.main_btn);  mListVIEw = (ListVIEw) findVIEwByID(R.ID.main_ListvIEw); } private voID initaction() {  mAudioRecorderbutton.setAudioFinishRecorderListener(new AudioRecorderbutton.AudioFinishRecorderListener() {   @OverrIDe   public voID onFinish(float time,String filePath) {    Recorder recorder = new Recorder((int)time,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) {    // 播放帧动画    mAnimVIEw = vIEw.findVIEwByID(R.ID.item_anim);    mAnimVIEw.setBackgroundResource(R.drawable.play_anim);    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(); }}

帧动画play_anim定义在drawable下

 <?xml version="1.0" enCoding="utf-8"?> <animation-List xmlns:androID="http://schemas.androID.com/apk/res/androID"  >  <item   androID:drawable="@mipmap/v_anim1"   androID:duration="300"/>  <item   androID:drawable="@mipmap/v_anim2"   androID:duration="300"/>  <item   androID:drawable="@mipmap/v_anim3"   androID:duration="300"/> </animation-List>

⑤最后,不要忘了添加权限

<uses-permission androID:name="androID.permission.RECORD_AUdio"/><uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission androID:name="androID.permission.MOUNT_UNMOUNT_fileSYstemS"/>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android仿微信、录制音频并发送功能全部内容,希望文章能够帮你解决Android仿微信、录制音频并发送功能所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1148913.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存