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

Android 錄音時獲取實時分貝值的代碼實例

編輯:關於 Android 程式設計

在做錄音、語音輸入等應用時,往往需要實時獲取當前的音量分貝值,用於展示波形或音量條。這可以借助 MediaRecorder 的 getMaxAmplitude() 方法來實現。下面是完整代碼:

public class MediaRecorderDemo {
    private final String TAG = "MediaRecord";
    private MediaRecorder mMediaRecorder;
    public static final int MAX_LENGTH = 1000 * 60 * 10; // 最大錄音時長
    private String filePath;

    public MediaRecorderDemo(){
        this.filePath = "/dev/null";
    }

    public MediaRecorderDemo(File file) {
        this.filePath = file.getAbsolutePath();
    }

    private long startTime;
    private long endTime;

    /** 開始錄音,使用 amr 格式 */
    public void startRecord() {
        if (mMediaRecorder == null)
            mMediaRecorder = new MediaRecorder();
        try {
            // 設置音頻源為麥克風
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            // 設置輸出格式
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
            // 設置音頻編碼為 AMR_NB
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

            mMediaRecorder.setOutputFile(filePath);
            mMediaRecorder.setMaxDuration(MAX_LENGTH);
            mMediaRecorder.prepare();
            mMediaRecorder.start();

            startTime = System.currentTimeMillis();
            updateMicStatus();
            Log.i("ACTION_START", "startTime" + startTime);
        } catch (IllegalStateException e) {
            Log.i(TAG, "call startAmr failed!" + e.getMessage());
        } catch (IOException e) {
            Log.i(TAG, "call startAmr failed!" + e.getMessage());
        }
    }

    /** 停止錄音 */
    public long stopRecord() {
        if (mMediaRecorder == null) return 0L;
        endTime = System.currentTimeMillis();
        mMediaRecorder.stop();
        mMediaRecorder.reset();
        mMediaRecorder.release();
        mMediaRecorder = null;
        Log.i("ACTION_LENGTH", "Time" + (endTime - startTime));
        return endTime - startTime;
    }

    private final Handler mHandler = new Handler();
    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateMicStatus();
        }
    };

    private int BASE = 1;
    private int SPACE = 100; // 間隔取樣時間(毫秒)

    /** 更新話筒狀態 */
    private void updateMicStatus() {
        if (mMediaRecorder != null) {
            double ratio = (double) mMediaRecorder.getMaxAmplitude() / BASE;
            double db = 0; // 分貝
            if (ratio > 1) db = 20 * Math.log10(ratio);
            Log.d(TAG, "分貝值:" + db);
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
        }
    }
}

關鍵在於定時調用 getMaxAmplitude() 拿到當前最大振幅,再通過 20*log10(振幅/參考值) 的公式換算成分貝,就能實時得到音量大小了。

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