編輯:關於 Android 開發
做聊天類 App 你一定見過這個效果:按著說話,介面上的圖示會隨著音量起伏跳動,微信、QQ 的語音輸入都是這樣。最近在開發一個帶錄音功能的小專案,就決定把這個互動做出來。折騰了一輪資料之後,這裡把完整的 Demo 思路整理出來分享給大家。
原理其實不複雜。核心只有一個 API:MediaRecorder.getMaxAmplitude(),它能取回當下的聲波振幅。拿到振幅後套上分貝公式 K = 20lg(Vo/Vi)(Vo 為當前振幅,Vi 為基準值,這裡取 500~600 之間),換算出分貝數,再依分貝區間切換 ImageView 上的圖片,跳動的效果就出來了。
下面依序拆解三個關鍵部分:對話框的初始化、振幅監聽介面,以及負責錄音的 RecodeManager。
先把七張不同高度的麥克風圖片備好,之後只要換背景就能產生「音量條」的錯覺:
public RecordDialog(Context context) {
this.context = context;
dialog_view = LayoutInflater.from(context).inflate(R.layout.dialog_sound, null);
// 初始化振幅圖片
progressImg[0] = context.getResources().getDrawable(R.drawable.mic_1);
progressImg[1] = context.getResources().getDrawable(R.drawable.mic_2);
progressImg[2] = context.getResources().getDrawable(R.drawable.mic_3);
progressImg[3] = context.getResources().getDrawable(R.drawable.mic_4);
progressImg[4] = context.getResources().getDrawable(R.drawable.mic_5);
progressImg[5] = context.getResources().getDrawable(R.drawable.mic_6);
progressImg[6] = context.getResources().getDrawable(R.drawable.mic_7);
dialog = new AlertDialog.Builder(context).setView(dialog_view).show();
progress = (ImageView) dialog_view.findViewById(R.id.sound_progress);
btn_cancel = (ImageView) dialog_view.findViewById(R.id.cancel);
btn_submit = (TextView) dialog_view.findViewById(R.id.submit);
mic_icon = (ImageView) dialog.findViewById(R.id.mic);
dialog_title = (TextView) dialog.findViewById(R.id.title);
txt_msg = (TextView) dialog.findViewById(R.id.msg);
btn_cancel.setOnClickListener(onCancel);
btn_submit.setOnClickListener(onSubmit);
}
定義一個 SoundAmplitudeListen 介面,把「收到分貝之後該怎麼顯示」這件事交給外部處理,錄音邏輯與 UI 就此解耦:
private SoundAmplitudeListen onSoundAmplitudeListen = new SoundAmplitudeListen() {
@Override
public void amplitude(int amplitude, int db, int value) {
// 最多對應到第七張圖
if (value >= 6) {
value = 6;
}
progress.setBackgroundDrawable(progressImg[value]);
}
};
這支類別負責建立錄音檔、啟動 MediaRecorder,並用 Handler 週期性換算振幅:
package com.example.voiceviewdemo;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.text.format.DateFormat;
public class RecodeManager {
private File file; // 錄音檔
private MediaRecorder mediaRecorder; // Android 媒體錄音類
private SoundAmplitudeListen soundAmplitudeListen; // 聲波振幅監聽器
private final Handler mHandler = new Handler();
private Runnable mUpdateMicStatusTimer = new Runnable() {
/** 分貝計算公式 K = 20lg(Vo/Vi),Vo 為當前振幅,Vi 為基準值 */
private int BASE = 500;
private int RATIO = 5;
private int postDelayed = 200; // 每 200ms 更新一次
@Override
public void run() {
int ratio = mediaRecorder.getMaxAmplitude() / BASE;
int db = (int) (20 * Math.log10(Math.abs(ratio)));
int value = db / RATIO;
if (value < 0) value = 0;
if (soundAmplitudeListen != null) {
soundAmplitudeListen.amplitude(ratio, db, value);
mHandler.postDelayed(mUpdateMicStatusTimer, postDelayed);
}
}
};
public void startRecordCreateFile() throws IOException {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
file = new File(Environment.getExternalStorageDirectory() + File.separator + "1"
+ File.separator
+ new DateFormat().format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA))
+ ".amr");
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setOutputFile(file.getAbsolutePath());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
mediaRecorder.prepare();
mediaRecorder.start();
mHandler.post(mUpdateMicStatusTimer);
}
public File stopRecord() {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
mHandler.removeCallbacks(mUpdateMicStatusTimer);
}
return file;
}
public void setSoundAmplitudeListen(SoundAmplitudeListen soundAmplitudeListen) {
this.soundAmplitudeListen = soundAmplitudeListen;
}
public interface SoundAmplitudeListen {
void amplitude(int amplitude, int db, int value);
}
}
這裡有幾個實作上值得留意的細節:BASE 與 RATIO 這兩個係數直接決定了跳動的靈敏度與格數,實際上線時大概要依真機測試反覆微調;postDelayed 的 200 毫秒則是更新頻率,調小會更順滑但也更耗電。另外别忘了在 stopRecord() 裡把 Handler 的 callback 移除,否則 Activity 銷毀後仍會殘留回呼。
實際跑起來的效果如下:

Demo 資源:https://download.csdn.net/detail/u014132820/9369346
順便附上幾個自己寫的小 App,有興趣可以試玩:
二維碼生成器:https://shouji.baidu.com/software/item?docid=8395189&from=as
古老讀心術:https://shouji.baidu.com/game/item?docid=8425923&from=as
打地鼠:https://shouji.baidu.com/game/item?docid=8409245&from=as
2048 軍銜版:https://shouji.baidu.com/game/item?docid=8372779&from=as
瘋狂的手指:https://shouji.baidu.com/game/item?docid=8269676&from=as
Android 事件總線 EventBus:讓元件通訊更簡潔
Android 事件總線 EventBus:讓元件通訊更簡潔 在 Android 中,Activity、Service、Fragment 之間要互相通訊往往相當麻煩,常見
Remote Displayer for Android V1.0:遠端手機畫面顯示工具
Remote Displayer for Android V1.0 功能說明 這款工具主要用於在電腦端遠端查看 Android 裝置畫面,並可進行螢幕擷取。使用時,電腦
Android 讀取 assets 與 raw 檔案內容
Android 讀取 assets 與 raw 檔案內容 Android 專案中,assets 與 res/raw 都可用來存放原始檔案,但讀取方式略有不同。assets
Android 記憶體洩漏排查與優化:從原理到 MAT、LeakCanary 實務
Android 記憶體洩漏與記憶體溢出解析 記憶體溢出是可用空間不足,記憶體洩漏則是物件無法釋放。兩者都可能導致應用崩潰,但排查方式不同。 Java 記憶體管理與洩漏