編輯:關於 Android 程式設計
微信的「按住說話」幾乎成了語音輸入的標準交互。它其實不難實現,核心就是一個自定義 Button 攔截觸摸事件,加上一個背景服務等級的錄音流程。本文把這個按鈕封裝成獨立控制項,並用策略模式把「錄音方式」與「介面互動」分開——這樣做有實際好處:一旦需求變成 wav 編碼,就不能再用 MediaRecorder,而必須換成 AudioRecord 自行處理 PCM 資料,介面層完全不必更動。

onTouchEvent,用按下/移動/抬起三個階段驅動整個錄音生命週期。ready() 與 start(),同時啟動計時線程。該線程每 100ms 讀取一次音量振幅,透過 Handler 依音量大小切換 Dialog 中的波形圖。recordEnd(filePath) 回調。<uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
public interface RecordStrategy {
/** 錄音準備:重置檔名、初始化錄音器 */
void ready();
/** 開始錄音 */
void start();
/** 結束錄音 */
void stop();
/** 錄音失敗或取消時刪除檔案 */
void deleteOldFile();
/** 取得當前音量振幅,用於驅動波形動畫 */
double getAmplitude();
/** 回傳錄音檔完整路徑 */
String getFilePath();
}
public class AudioRecorder implements RecordStrategy {
private MediaRecorder recorder;
private String fileName;
private final String fileFolder =
Environment.getExternalStorageDirectory().getPath() + "/TestRecord";
private boolean isRecording = false;
@Override
public void ready() {
File file = new File(fileFolder);
if (!file.exists()) {
file.mkdirs();
}
fileName = getCurrentDate();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(fileFolder + "/" + fileName + ".amr");
}
/** 以當前時間作為檔名,避免覆蓋 */
private String getCurrentDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
return formatter.format(new Date(System.currentTimeMillis()));
}
@Override
public void start() {
if (!isRecording) {
try {
recorder.prepare();
recorder.start();
isRecording = true;
} catch (IOException | IllegalStateException e) {
e.printStackTrace();
}
}
}
@Override
public void stop() {
if (isRecording) {
recorder.stop();
recorder.release();
recorder = null;
isRecording = false;
}
}
@Override
public void deleteOldFile() {
new File(fileFolder + "/" + fileName + ".amr").deleteOnExit();
}
@Override
public double getAmplitude() {
return isRecording ? recorder.getMaxAmplitude() : 0;
}
@Override
public String getFilePath() {
return fileFolder + "/" + fileName + ".amr";
}
}
要換成 AudioRecord 方案時,只需新寫一個實作類,在 ready 中配置取樣率與位元、在 start 中啟動錄音線程自行讀取 PCM 資料,介面層一行都不用改。
public class RecordButton extends Button {
private static final int MIN_RECORD_TIME = 1; // 最短錄音秒數
private static final int RECORD_OFF = 0;
private static final int RECORD_ON = 1;
private Dialog mRecordDialog;
private RecordStrategy mAudioRecorder;
private Thread mRecordThread;
private RecordListener listener;
private int recordState = RECORD_OFF;
private float recodeTime = 0.0f;
private double voiceValue = 0.0;
private boolean isCanceled = false;
private float downY;
private ImageView dialogImg;
private TextView dialogTextView;
private Context mContext;
public RecordButton(Context context) {
super(context);
init(context);
}
public RecordButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public RecordButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mContext = context;
setText("按住 說話");
}
public void setAudioRecord(RecordStrategy record) {
this.mAudioRecorder = record;
}
public void setRecordListener(RecordListener listener) {
this.listener = listener;
}
/** 顯示錄音浮層,flag=1 表示即將取消 */
private void showVoiceDialog(int flag) {
if (mRecordDialog == null) {
mRecordDialog = new Dialog(mContext, R.style.Dialogstyle);
mRecordDialog.setContentView(R.layout.dialog_record);
dialogImg = mRecordDialog.findViewById(R.id.record_dialog_img);
dialogTextView = mRecordDialog.findViewById(R.id.record_dialog_txt);
}
if (flag == 1) {
dialogImg.setImageResource(R.drawable.record_cancel);
dialogTextView.setText("鬆開手指可取消錄音");
setText("鬆開手指 取消錄音");
} else {
dialogImg.setImageResource(R.drawable.record_animate_01);
dialogTextView.setText("向上滑動可取消錄音");
setText("鬆開手指 完成錄音");
}
dialogTextView.setTextSize(14);
mRecordDialog.show();
}
/** 依音量切換波形圖,避免十幾個 if-else 可用亮度分檔 + 圖片陣列 */
private void setDialogImage() {
int[] frames = {
R.drawable.record_animate_01, R.drawable.record_animate_02,
R.drawable.record_animate_03, R.drawable.record_animate_04
// ... 依需要補齊更多幀
};
int index = (int) Math.min(voiceValue / 1000.0, frames.length - 1);
dialogImg.setImageResource(frames[index]);
}
private void showWarnToast() {
Toast toast = new Toast(mContext);
toast.setView(LayoutInflater.from(mContext).inflate(R.layout.toast_warn, null));
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
private final Runnable recordThread = new Runnable() {
@Override
public void run() {
recodeTime = 0.0f;
while (recordState == RECORD_ON) {
try {
Thread.sleep(100);
recodeTime += 0.1;
if (!isCanceled) {
voiceValue = mAudioRecorder.getAmplitude();
recordHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
private final Handler recordHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
setDialogImage();
}
};
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (recordState != RECORD_ON && mAudioRecorder != null) {
showVoiceDialog(0);
downY = event.getY();
mAudioRecorder.ready();
recordState = RECORD_ON;
mAudioRecorder.start();
mRecordThread = new Thread(recordThread);
mRecordThread.start();
}
break;
case MotionEvent.ACTION_MOVE:
float moveY = event.getY();
if (downY - moveY > 50) {
isCanceled = true;
showVoiceDialog(1);
} else if (downY - moveY < 20) {
isCanceled = false;
showVoiceDialog(0);
}
break;
case MotionEvent.ACTION_UP:
if (recordState == RECORD_ON) {
recordState = RECORD_OFF;
if (mRecordDialog != null && mRecordDialog.isShowing()) {
mRecordDialog.dismiss();
}
mAudioRecorder.stop();
if (mRecordThread != null) {
mRecordThread.interrupt();
}
voiceValue = 0.0;
if (isCanceled) {
mAudioRecorder.deleteOldFile();
} else if (recodeTime < MIN_RECORD_TIME) {
showWarnToast();
mAudioRecorder.deleteOldFile();
} else if (listener != null) {
listener.recordEnd(mAudioRecorder.getFilePath());
}
isCanceled = false;
setText("按住 說話");
}
break;
}
// 必須回傳 true,才能持續接收滑出範圍後的 MOVE / UP 事件
return true;
}
public interface RecordListener {
void recordEnd(String filePath);
}
}
<!-- dialog_record.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/record_bg"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">
<ImageView
android:id="@+id/record_dialog_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/record_dialog_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textColor="@android:color/white" />
</LinearLayout>
<!-- 對話框樣式:去掉系統邊框與背景,避免浮層邊角露出 -->
<style name="Dialogstyle">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
public class MainActivity extends Activity {
private RecordButton button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn_record);
button.setAudioRecord(new AudioRecorder());
button.setRecordListener(filePath -> {
// 拿到錄音檔路徑,接下來上傳、轉文字或播放都可以
Log.i("record", filePath);
});
}
}
Android 6.0 應用啟動全流程源碼深度剖析
以下分析基於 API 23(Android 6.0)。想真正搞懂一個 App 是怎麼從桌面圖標被點亮、一路走到 Activity 呈現在眼前的,那就得潛進源碼,順著調用鏈
Android AdapterView 與 Adapter 完全解析:Spinner 與 ListView 實戰
一、適配器視圖與適配器的定位 AdapterView 繼承自 ViewGroup,顧名思義是「需要適配器的視圖容器」。常見的成員包括 Spinner、ListView、G
Android EventBus 源碼解析
1. 功能介紹 1.1 EventBus EventBus 是一個 Android 事件發布/訂閱框架,透過解耦發布者與訂閱者來簡化事件傳遞。這裡的「事件」可理解為消息,
Android RecyclerView 快速入門:從線性列表到瀑布流
第一次接觸 RecyclerView 的人常有一種錯覺:怎麼比 ListView 還麻煩?其實它的「麻煩」換來的是更高的自由度——列表、格線、瀑布流都只要換一個 Layo