Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

仿微信語音對講:自定義錄音按鈕與策略模式解耦實作

編輯:關於 Android 程式設計

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

實現思路

  1. 控制項基礎:自定義 RecordButton 繼承 Button,重寫 onTouchEvent,用按下/移動/抬起三個階段驅動整個錄音生命週期。
  2. 按下(ACTION_DOWN):彈出自定義 Dialog 提示浮層,呼叫錄音策略的 ready() 與 start(),同時啟動計時線程。該線程每 100ms 讀取一次音量振幅,透過 Handler 依音量大小切換 Dialog 中的波形圖。
  3. 移動(ACTION_MOVE):以上移距離判斷是否取消。上移超過閾值(例如 50px)時切換為「鬆開手指 取消錄音」狀態並將 isCanceled 標記為 true;手指回落(位移小於 20px)則還原提示並取消標記。這裡刻意用兩個不同閾值形成緩衝區,避免在邊界處反覆跳動。
  4. 抬起(ACTION_UP):關閉浮層、停止錄音並結束計時線程,接著依序判斷:是否已取消 → 錄音時長是否過短 → 都通過才觸發 recordEnd(filePath) 回調。
  5. 策略模式:把「如何錄音」抽象成 RecordStrategy 介面(準備、開始、停止、取音量、取路徑、刪除檔案),每種錄音實作就是一種策略,執行期注入即可替換。

兩個必須注意的細節

  • onTouchEvent 要回傳 true。若回傳 false,手指一旦滑出 Button 範圍,後續的 MOVE 與 UP 事件就會被其他控制項接手,導致錄音無法停止。回傳 true 才能完整吃下整段手勢。
  • 權限別忘了申請,Android 6.0 以上還需要執行期動態請求:
<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();
}

基於 MediaRecorder 的策略實作

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);
        });
    }
}

實作上的幾個補充

  • 閾值別寫死:取消手勢的 50/20 是像素值,不同螢幕密度上手感會差很多,實務上建議依 density 換算成 dp。
  • Activity 銷毀時要收尾:在 onDestroy 中呼叫 stop 並 dismiss 浮層,否則螢幕旋轉或返回時容易泄漏 Window。
  • 振幅映射要平滑:getMaxAmplitude 是區間最大值,直接映射容易抖動,可加上加權平均或分檔遲滯,波形看起來會自然很多。
  • 存储位置:Android 10 以上建議改用 app 專用目錄或 MediaStore,避免直接寫外部儲存根目錄。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved