您好,登錄后才能下訂單哦!
小編給大家分享一下Android如何實現仿微信語音消息的錄制和播放功能,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
一、簡述
效果:
實現功能:
長按Button時改變Button顯示文字,彈出Dialog(動態更新音量),動態生成錄音文件,開始錄音;
監聽手指動作,規定區域。錄音狀態下手指劃出規定區域取消錄音,刪除生成的錄音文件;
監聽手指動作。當手指抬起時,判斷是否開始錄音,錄音時長是否過短,符合條件則提示錄音時長過短;正常結束時通過回調返回該次錄音的文件路徑和時長。
4.點擊錄音列表的item時,播放動畫,播放對應的音頻文件。
主要用到4個核心類:
自定義錄音按鈕(AudioRecordButton);
彈框管理類(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如何實現仿微信語音消息的錄制和播放功能”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。