Android模仿微信语音聊天功能
项目效果如下:
项目目录结构如下:
代码如下:
AudioManager.java
import java.io.File;
import java.io.IOException;
import java.util.UUID; import android.media.MediaRecorder; public class AudioManager {
private MediaRecorder mMediaRecorder;
private String mDir;
private String mCurrentFilePath; private static AudioManager mInstance; private boolean isPrepare; private AudioManager(String dir) {
mDir = dir;
} public static AudioManager getInstance(String dir) {
if (mInstance == null) {
synchronized (AudioManager.class) {
if (mInstance == null) {
mInstance = new AudioManager(dir);
}
}
}
return mInstance;
} /**
* 使用接口 用于回调
*/
public interface AudioStateListener {
void wellPrepared();
} public AudioStateListener mAudioStateListener; /**
* 回调方法
*/
public void setOnAudioStateListener(AudioStateListener listener) {
mAudioStateListener = listener;
} // 去准备
public void prepareAudio() {
try {
isPrepare = 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(dir.getAbsolutePath());
// 设置MediaRecorder的音频源为麦克风
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 设置音频格式
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
// 设置音频编码
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 准备录音
mMediaRecorder.prepare();
// 开始
mMediaRecorder.start();
// 准备结束
isPrepare = true;
if (mAudioStateListener != null) {
mAudioStateListener.wellPrepared();
} } catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} } /**
* 随机生成文件的名称
*/
private String generateFileName() {
return UUID.randomUUID().toString() + .amr;
} public int getVoiceLevel(int maxlevel) {
if (isPrepare) {
try {
// mMediaRecorder.getMaxAmplitude() 1~32767
return maxlevel * mMediaRecorder.getMaxAmplitude() / + ;
} catch (Exception e) {
}
}
return ;
} /**
* 释放资源
*/
public void release() {
//mMediaRecorder.stop();
mMediaRecorder.reset();
mMediaRecorder = null;
} /**
* 取消录音
*/
public void cancel() {
release();
if (mCurrentFilePath != null) {
File file = new File(mCurrentFilePath);
file.delete();
mCurrentFilePath = null;
} } public String getCurrentFilePath() { return mCurrentFilePath;
}
}
AudioRecorderButton.java
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.xuliugen.weichat.R;
import com.xuliugen.weichat.AudioManager.AudioStateListener; public class AudioRecorderButton extends Button { private static final int STATE_NORMAL = ;// 默认的状态
private static final int STATE_RECORDING = ;// 正在录音
private static final int STATE_WANT_TO_CANCEL = ;// 希望取消 private int mCurrentState = STATE_NORMAL; // 当前的状态
private boolean isRecording = false;// 已经开始录音 private static final int DISTANCE_Y_CANCEL = ; private DialogManager mDialogManager;
private AudioManager mAudioManager; private float mTime;
// 是否触发longClick
private boolean mReady; private static final int MSG_AUDIO_PREPARED = 0x110;
private static final int MSG_VOICE_CHANGED = 0x111;
private static final int MSG_DIALOG_DIMISS = 0x112; /*
* 获取音量大小的线程
*/
private Runnable mGetVoiceLevelRunnable = new Runnable() { public void run() {
while (isRecording) {
try {
Thread.sleep();
mTime += 0.1f;
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:
// 显示對話框在开始录音以后
mDialogManager.showRecordingDialog();
isRecording = true;
// 开启一个线程
new Thread(mGetVoiceLevelRunnable).start();
break; case MSG_VOICE_CHANGED:
mDialogManager.updateVoiceLevel(mAudioManager.getVoiceLevel());
break; case MSG_DIALOG_DIMISS:
mDialogManager.dimissDialog();
break; } super.handleMessage(msg);
}
}; /**
* 以下2个方法是构造方法
*/
public AudioRecorderButton(Context context, AttributeSet attrs) {
super(context, attrs);
mDialogManager = new DialogManager(context); String dir = /storage/sdcard0/my_weixin;
//String dir = Environment.getExternalStorageDirectory()+/my_weixin; mAudioManager = AudioManager.getInstance(dir);
mAudioManager.setOnAudioStateListener(new AudioStateListener() { public void wellPrepared() {
mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
}
}); // 由于这个类是button所以在构造方法中添加监听事件
setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View v) {
mReady = true; mAudioManager.prepareAudio(); return false;
}
});
} public AudioRecorderButton(Context context) {
this(context, null);
} /**
* 录音完成后的回调
*/
public interface AudioFinishRecorderListener {
void onFinish(float seconds, String filePath);
} private AudioFinishRecorderListener audioFinishRecorderListener; public void setAudioFinishRecorderListener(AudioFinishRecorderListener listener) {
audioFinishRecorderListener = listener;
} /**
* 屏幕的触摸事件
*/
@Override
public boolean onTouchEvent(MotionEvent event) { int action = event.getAction();
int x = (int) event.getX();// 获得x轴坐标
int y = (int) event.getY();// 获得y轴坐标 switch (action) {
case MotionEvent.ACTION_DOWN:
changeState(STATE_RECORDING);
break;
case MotionEvent.ACTION_MOVE: if (isRecording) {
// 如果想要取消,根据x,y的坐标看是否需要取消
if (wantToCancle(x, y)) {
changeState(STATE_WANT_TO_CANCEL);
} else {
changeState(STATE_RECORDING);
}
} break;
case MotionEvent.ACTION_UP:
if (!mReady) {
reset();
return super.onTouchEvent(event);
}
if (!isRecording || mTime < 0.6f) {
mDialogManager.tooShort();
mAudioManager.cancel();
mHandler.sendEmptyMessageDelayed(MSG_DIALOG_DIMISS, );// 延迟显示对话框
} else if (mCurrentState == STATE_RECORDING) { // 正在录音的时候,结束
mDialogManager.dimissDialog();
mAudioManager.release(); if (audioFinishRecorderListener != null) {
audioFinishRecorderListener.onFinish(mTime,mAudioManager.getCurrentFilePath());
} } else if (mCurrentState == STATE_WANT_TO_CANCEL) { // 想要取消
mDialogManager.dimissDialog();
mAudioManager.cancel();
}
reset();
break; }
return super.onTouchEvent(event);
} /**
* 恢复状态及标志位
*/
private void reset() {
isRecording = false;
mTime = ;
mReady = false;
changeState(STATE_NORMAL);
} private boolean wantToCancle(int x, int y) {
if (x < || x > getWidth()) { // 超过按钮的宽度
return true;
}
// 超过按钮的高度
if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
return true;
} return false;
} /**
* 改变
*/
private void changeState(int state) {
if (mCurrentState != state) {
mCurrentState = 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_TO_CANCEL:
setBackgroundResource(R.drawable.btn_recorder_recording);
setText(R.string.str_recorder_want_cancel); mDialogManager.wantToCancel();
break;
}
}
}
}
DialogManager.java
import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView; import com.xuliugen.weichat.R; /**
* 用于管理Dialog
*
* @author xuliugen
*
*/
public class DialogManager { private AlertDialog.Builder builder;
private ImageView mIcon;
private ImageView mVoice;
private TextView mLable; private Context mContext; private AlertDialog dialog;//用于取消AlertDialog.Builder /**
* 构造方法 传入上下文
*/
public DialogManager(Context context) {
this.mContext = context;
} // 显示录音的对话框
public void showRecordingDialog() { builder = new AlertDialog.Builder(mContext, R.style.AudioDialog);
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.dialog_recorder,null); mIcon = (ImageView) view.findViewById(R.id.id_recorder_dialog_icon);
mVoice = (ImageView) view.findViewById(R.id.id_recorder_dialog_voice);
mLable = (TextView) view.findViewById(R.id.id_recorder_dialog_label); builder.setView(view);
builder.create();
dialog = builder.show();
} public void recording(){
if(dialog != null && dialog.isShowing()){ //显示状态
mIcon.setVisibility(View.VISIBLE);
mVoice.setVisibility(View.VISIBLE);
mLable.setVisibility(View.VISIBLE); mIcon.setImageResource(R.drawable.recorder);
mLable.setText(手指上滑,取消发送);
}
} // 显示想取消的对话框
public void wantToCancel() {
if(dialog != null && dialog.isShowing()){ //显示状态
mIcon.setVisibility(View.VISIBLE);
mVoice.setVisibility(View.GONE);
mLable.setVisibility(View.VISIBLE); mIcon.setImageResource(R.drawable.cancel);
mLable.setText(松开手指,取消发送);
}
} // 显示时间过短的对话框
public void tooShort() {
if(dialog != null && dialog.isShowing()){ //显示状态
mIcon.setVisibility(View.VISIBLE);
mVoice.setVisibility(View.GONE);
mLable.setVisibility(View.VISIBLE); mIcon.setImageResource(R.drawable.voice_to_short);
mLable.setText(录音时间过短);
}
} // 显示取消的对话框
public void dimissDialog() {
if(dialog != null && dialog.isShowing()){ //显示状态
dialog.dismiss();
dialog = null;
}
} // 显示更新音量级别的对话框
public void updateVoiceLevel(int level) {
if(dialog != null && dialog.isShowing()){ //显示状态
// mIcon.setVisibility(View.VISIBLE);
// mVoice.setVisibility(View.VISIBLE);
// mLable.setVisibility(View.VISIBLE); //设置图片的id
int resId = mContext.getResources().getIdentifier(v+level, drawable, mContext.getPackageName());
mVoice.setImageResource(resId);
}
} }
MainActivity.java
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener; public class MediaManager { private static MediaPlayer mMediaPlayer;
private static boolean isPause; /**
* 播放音乐
* @param filePath
* @param onCompletionListener
*/
public static void playSound(String filePath,OnCompletionListener onCompletionListener) {
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer(); //设置一个error监听器
mMediaPlayer.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
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) { }
} /**
* 暂停播放
*/
public static void pause() {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { //正在播放的时候
mMediaPlayer.pause();
isPause = true;
}
} /**
* 当前是isPause状态
*/
public static void resume() {
if (mMediaPlayer != null && isPause) {
mMediaPlayer.start();
isPause = false;
}
} /**
* 释放资源
*/
public static void release() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
}
RecoderAdapter.java
import java.util.List; import android.content.Context;
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.xuliugen.weichat.MainActivity.Recorder; public class RecoderAdapter extends ArrayAdapter<recorder> { private Context mContext;
private List<recorder> mDatas; private int mMinItemWidth; //最小的item宽度
private int mMaxItemWidth; //最大的item宽度
private LayoutInflater mInflater; public RecoderAdapter(Context context, List<recorder> datas) {
super(context, -, datas); mContext = context;
mDatas = datas; //获取屏幕的宽度
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
mMaxItemWidth = (int) (outMetrics.widthPixels * 0.7f);
mMinItemWidth = (int) (outMetrics.widthPixels * 0.15f); mInflater = LayoutInflater.from(context);
} /**
* 定义一个ViewHolder
*/
private class ViewHolder {
TextView seconds; // 时间
View length; // 长度
} @Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_recoder, parent,false);
holder = new ViewHolder();
holder.seconds = (TextView) convertView.findViewById(R.id.id_recoder_time);
holder.length = convertView.findViewById(R.id.id_recoder_lenght); convertView.setTag(holder); } else {
holder = (ViewHolder) convertView.getTag();
}
holder.seconds.setText(Math.round(getItem(position).time) + );
ViewGroup.LayoutParams lp = holder.length.getLayoutParams();
lp.width = (int) (mMinItemWidth + (mMaxItemWidth / 60f)* getItem(position).time);
return convertView;
}
}
Android模仿微信语音聊天功能的更多相关文章
- js模仿微信语音播放的小功能
自己写的一个模仿微信语音播放的小功能,实现的主要功能是:点击播放,点击暂停,播放切换,,, 代码如下: <!DOCTYPE html> <html lang="en&qu ...
- Android 高仿微信语音聊天页面高斯模糊效果
目前的应用市场上,使用毛玻璃效果的APP随处可见,比如用过微信语音聊天的人可以发现,语音聊天页面就使用了高斯模糊效果. 先看下效果图: 仔细观察上图,我们可以发现,背景图以用户头像为模板,对其进行了高 ...
- uniapp+nvue开发之仿微信语音+视频通话功能 :实现一对一语音视频在线通话
本篇文章是利用uni-app和nvue实现微信效果功能的第三篇了,今天我们基于uniapp + nvue实现的uniapp仿微信音视频通话插件实例项目,实现了以下功能: 1: 语音通话 2: 视频 ...
- 转-Android仿微信气泡聊天界面设计
微信的气泡聊天是仿iPhone自带短信而设计出来的,不过感觉还不错可以尝试一下仿着微信的气泡聊天做一个Demo,给大家分享一下!效果图如下: 气泡聊天最终要的是素材,要用到9.png文件的素材,这样气 ...
- Android 模仿微信启动动画(转)
本文内容 环境 项目结构 演示微信启动动画 本文演示微信启动动画.请点击此处下载,自行调试. 顺便抱怨一下,实践性(与研究性质的相对)技术博的“七宗罪”: 第一宗罪,错字连篇,逻辑不清: 第二宗罪,文 ...
- Android仿微信气泡聊天界面设计
微信的气泡聊天是仿iPhone自带短信而设计出来的,不过感觉还不错可以尝试一下仿着微信的气泡聊天做一个Demo,给大家分享一下!效果图如下: 气泡聊天最终要的是素材,要用到9.png文件的素材,这样气 ...
- Android 模仿微信启动动画
本文内容 环境 项目结构 演示微信启动动画 本文演示微信启动动画.请点击此处下载,自行调试. 顺便抱怨一下,实践性(与研究性质的相对)技术博的"七宗罪": 第一宗罪,错字连篇,逻辑 ...
- Android 模仿微信发送图片 钟罩效果
参考资料http://trylovecatch.iteye.com/blog/1189452 http://bbs.51cto.com/thread-1031415-1.html### 1.添加资源文 ...
- Android仿微信SlideView聊天列表滑动删除效果
package com.ryg.slideview; import com.ryg.slideview.MainActivity.MessageItem; //Download by http://w ...
随机推荐
- Javascript中&&和&,||和|运算符两个不同点
1.性能上的比较 如果&&的第一个运算数是false,就不再考虑第二个运算数,直接返回false:如 果||的第一个运算数是true,也不再考虑第二个运算数,直接返回true.& ...
- 简单计算器(Android)
aaarticlea/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKC
- Squid--hash代码分析
#ifndef SQUID_HASH_H #define SQUID_HASH_H //几个函数和变量的别名 typedef void HASHFREE(void *); typedef int HA ...
- javascript笔记7之对象数组
/* var box = new Array(); //声明一个数组,空数组 alert(typeof box); //数组属于object类型 var box = new Array('李炎恢', ...
- JAVA模拟表单提交
这是我网上搜的,自己使用也蛮方便,所以上传供大家分享. package wzh.Http; import java.io.BufferedReader; import java.io.IOExce ...
- hibernate-4.3.5安装配置
起初照着官方文档配,一直出错,貌似官方的文档时错的,查了非常多资料,综合整理了一个可行的方案,例如以下: 0.1包结构 test.demo test.domain //实体类 test.util// ...
- Mybatis分页插件PageHelper正确的用法(网上有2篇不够科学的文章)
今天下午在Mybatis项目中.实现分页.由于我是后加入项目中的,Leader用的是PageHelper这个组件.可是我在实际使用的过程中遇到了2个大问题. 1.p=2#comments" ...
- ajax(ajax开发)
AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术. AJAX = 异步 JavaScript和 ...
- 在WIN7系统下用Quartus ii 11.1 NIOS II 11.1 有时候会出现Nios II 的Run as hardware 中报错:Downloading ELF Process failed
nios工程在编译通过后RUN的过程中出现Error Running Nios II Project: ‘Downloading ELF Process failed’问题原因: 1.nios2 cp ...
- ncsim仿真VHDL
ncsim仿真VHDL 1.文件列表 ctrl.vhd design_io.vhd tb.vhd compile.nc simulate.nc ./shm/shmtb.tcl 2. Compile你的 ...