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

Android 錄音與音頻播放功能完整實現教程

編輯:關於 Android 程式設計

本文記錄了一個錄製聲音文件並播放的完整 Demo 實現過程,供需要的朋友參考。

先說明幾點注意事項:其一,這個 Demo 未對「多次快速點擊同一個音頻文件」做完善處理,偶爾會崩潰,使用時需留意;其二,按住錄音按鈕的過程中只處理了豎屏方向,橫屏未做适配;其三,未單獨實現刪除音頻的操作,但相關邏輯已在 MainActivity 的 onItemClick 中以 TODO 註釋標明;其四,這僅是一個演示性 Demo,若要引入正式專案,建議先跑通 Demo 再集成。此外,在真機上運行時若彈出錄音權限申請,最好選擇「允許」,否則可能導致崩潰。

記得先在系統設置中開啟錄音權限。

目錄結構

1. 添加權限

首先在 AndroidManifest.xml 中聲明錄音與存儲相關的權限:

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

2. 錄音工具類 MediaRecorderUtils

核心錄音邏輯封裝在 MediaRecorderUtils 中,負責初始化 MediaRecorder、開始/停止錄音、實時音量回調以及刪除文件:

package com.chen.voicedemo;

import android.media.MediaRecorder;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import java.io.File;

/** 錄音工具類 */
public class MediaRecorderUtils {
    private static MediaRecorder recorder;
    static MediaRecorderUtils mediaRecorderUtils;
    static ImageView mimageView;
    private String path;

    /** 獲得單例物件,傳入一個顯示音量大小的 ImageView,如不需要可傳 null */
    public static MediaRecorderUtils getInstence(ImageView imageView) {
        if (mediaRecorderUtils == null) {
            mediaRecorderUtils = new MediaRecorderUtils();
        }
        mimageView = imageView;
        return mediaRecorderUtils;
    }

    public String getPath() {
        return path;
    }

    /** 初始化 */
    private void init() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);      // 音頻源為麥克風
        recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR); // 輸出格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);  // 編碼為 amr
        File file = new File(Utils.IMAGE_SDCARD_MADER);
        if (!file.exists()) {
            file.mkdirs();
        }
        path = Utils.IMAGE_SDCARD_MADER + Utils.getVoiceFileName() + "stock.amr";
        recorder.setOutputFile(path);
        try {
            recorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 開始錄音 */
    public void MediaRecorderStart() {
        init();
        try {
            recorder.start();
            flag = true;
            if (mimageView != null) {
                updateMicStatus();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("chen", "錄制失敗");
        }
    }

    /** 停止錄音 */
    public void MediaRecorderStop() {
        try {
            recorder.stop();
            recorder.release();
            flag = false;
            mimageView = null;
            recorder = null;
        } catch (Exception e) {
            e.toString();
        }
    }

    /** 刪除已錄制的音頻 */
    public void MediaRecorderDelete() {
        File file = new File(path);
        if (file.isFile()) {
            file.delete();
        }
    }

    private final Handler mHandler = new Handler();
    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateMicStatus();
        }
    };
    private int BASE = 1;
    private int SPACE = 1000;   // 間隔取樣時間
    private boolean flag = true;

    /** 更新話筒音量狀態 */
    private void updateMicStatus() {
        if (recorder != null) {
            double ratio = (double) recorder.getMaxAmplitude() / BASE;
            double db = 0;
            if (ratio > 1) {
                db = 20 * Math.log10(ratio);
            }
            int i = (int) db / 10;
            switch (i) {
                case 1: mimageView.setImageResource(R.drawable.rc_ic_volume_1); break;
                case 2: mimageView.setImageResource(R.drawable.rc_ic_volume_2); break;
                case 3: mimageView.setImageResource(R.drawable.rc_ic_volume_3); break;
                case 4: mimageView.setImageResource(R.drawable.rc_ic_volume_4); break;
                case 5: mimageView.setImageResource(R.drawable.rc_ic_volume_5); break;
                case 6: mimageView.setImageResource(R.drawable.rc_ic_volume_6); break;
                case 7: mimageView.setImageResource(R.drawable.rc_ic_volume_7); break;
                case 8: mimageView.setImageResource(R.drawable.rc_ic_volume_8); break;
            }
            if (flag) {
                mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
            }
        }
    }
}

3. 自定義計時器 MyChronometer

為了在錄音過程中展示實時時長,自定義了一個 MyChronometer 視圖,它繼承自 TextView,通過 Handler 週期性刷新顯示,並在停止時通過接口回調最終時長。

public class MyChronometer extends TextView {
    public interface OnMyChronometerTickListener {
        void onMyChronometerTick(int time);
    }
    public interface OnMyChronometerTimeListener {
        void OnMyChronometerTimeListener(int time);
    }
    private OnMyChronometerTimeListener OnMyChronometerTimeListener;
    private long mBase;
    private boolean mVisible;
    private boolean mStarted;
    private boolean mRunning;
    private OnMyChronometerTickListener mOnMyChronometerTickListener;
    private long now_time;
    private static final int TICK_WHAT = 2;

    public MyChronometer(Context context) { this(context, null, 0); }
    public MyChronometer(Context context, AttributeSet attrs) { this(context, attrs, 0); }
    public MyChronometer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        mBase = SystemClock.elapsedRealtime();
        updateText(mBase);
    }

    public void setBase(long base) {
        mBase = base;
        updateText(SystemClock.elapsedRealtime());
    }

    public void setOnMyChronometerTickListener(OnMyChronometerTickListener listener) {
        mOnMyChronometerTickListener = listener;
    }

    public void setOnMyChronometerTimeListener(OnMyChronometerTimeListener listener) {
        OnMyChronometerTimeListener = listener;
    }

    public void start() {
        mStarted = true;
        updateRunning();
    }

    public void stop() {
        mStarted = false;
        updateRunning();
        now_time /= 10;
        if (OnMyChronometerTimeListener != null) {
            OnMyChronometerTimeListener.OnMyChronometerTimeListener((int) now_time);
        }
    }

    @Override protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mVisible = false;
        updateRunning();
    }

    @Override protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        mVisible = visibility == VISIBLE;
        updateRunning();
    }

    private synchronized void updateText(long now) {
        long seconds = now - mBase;
        seconds /= 10;
        now_time = seconds;
        int time_m = (int) (seconds / 100);
        if (mOnMyChronometerTickListener != null) {
            mOnMyChronometerTickListener.onMyChronometerTick(time_m);
        }
        setText(time_m + "");
    }

    private void updateRunning() {
        boolean running = mVisible && mStarted;
        if (running != mRunning) {
            if (running) {
                updateText(SystemClock.elapsedRealtime());
                mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), 1000);
            } else {
                mHandler.removeMessages(TICK_WHAT);
            }
            mRunning = running;
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message m) {
            if (mRunning) {
                updateText(SystemClock.elapsedRealtime());
                sendMessageDelayed(Message.obtain(this, TICK_WHAT), 1000);
            }
        }
    };
}

4. 工具類 Utils

Utils 類負責存儲路徑定義、6.0 及以上版本的錄音權限檢查、Toast 單例以及音頻文件命名等通用功能:

public class Utils {
    /** SD 卡下語音目錄 */
    public static final String IMAGE_SDCARD_MADER =
            Environment.getExternalStorageDirectory() + "/chen/voice/";

    /** 檢查錄音權限(6.0) */
    public static boolean checkVoice(Context context) {
        try {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return true;
        }
    }

    /** 獲取指定文件夾下的所有文件路徑 */
    public static ArrayList<String> getVideoFiles(String root) {
        if (root == null || root == "") return null;
        ArrayList<String> list = new ArrayList<>();
        File file = new File(root);
        File[] fileList = file.listFiles();
        for (File f : fileList) {
            list.add(f.getPath());
        }
        return list;
    }

    /** 獲取聲音文件名,以毫秒時間戳格式化,保證唯一性 */
    public static String getVoiceFileName() {
        long getNowTimeLong = System.currentTimeMillis();
        SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmss");
        return time.format(getNowTimeLong);
    }
}

5. MainActivity 核心邏輯

MainActivity 負責整合錄音按鈕的觸摸事件、彈窗展示、音頻列表以及播放控制。錄音按鈕的 onTouch 事件中處理了按下、移動(上滑取消)、抬起等狀態;點擊列表項則調用 MediaPlayer 播放對應音頻,並配合幀動畫展示播放狀態。

// 錄音按鈕 onTouch 關鍵邏輯節選
@Override
public boolean onTouch(View v, MotionEvent event) {
    if (v.getId() == R.id.voice) {
        if (!Utils.checkVoice(this)) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                Utils.showToast(this, "錄音權限未打開,請打開錄音權限!");
            }
            return true;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                VoicePopupWindow();
                mychronometer.setBase(SystemClock.elapsedRealtime());
                mychronometer.start();
                MediaRecorderUtils.getInstence(voice_shengyin).MediaRecorderStart();
                flag = true;
                break;
            case MotionEvent.ACTION_MOVE:
                // 上滑超過閾值則取消錄音並刪除文件
                if (flag && Math.abs(int_y) - Math.abs(event.getRawY()) > 100.0) {
                    voice_popupWindow.dismiss();
                    mychronometer.stop();
                    MediaRecorderUtils.getInstence(voice_shengyin).MediaRecorderStop();
                    MediaRecorderUtils.getInstence(voice_shengyin).MediaRecorderDelete();
                    flag = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (flag) { setVoiceToUp(); }
                break;
        }
        return true;
    }
    return false;
}

6. 布局文件

activity_main 布局包含錄音按鈕、音頻列表、播放動畫 ImageView 以及停止播放按鈕等元素;voice_popupwindow 則是錄音時弹出的浮層,內含音量波形圖與計時器。

7. 播放動畫

播放音頻時,通過幀動畫(animation-list)呈現動態效果:

<animation-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/rc_ic_voice_receive_play1" android:duration="100" />
    <item android:drawable="@drawable/rc_ic_voice_receive_play2" android:duration="200" />
    <item android:drawable="@drawable/rc_ic_voice_receive_play3" android:duration="300" />
</animation-list>

附錄:圖片資源說明——若手上沒有合適的圖片,可隨意用其他圖片代替,只要能呈現效果即可。


至此,一個具備錄音、實時音量反饋、計時、上滑取消、列表展示與播放動畫的完整錄音 Demo 就實現了。實際集成到專案時,還需補充完善橫屏适配、快速重複點擊防抖以及刪除等細節處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved