Android 即時擷取麥克風輸入音量的代碼

來源:互聯網
上載者:User

http://www.mikespook.com/index.php/archives/762

 

 

Android 上有一些很有趣的應用,例如《吹裙子》、《吹氣球》之類的。利用的是即時擷取麥克風輸入音量,然後進行相應的處理。網上也不少人問如何處理這個事情,也有一些解答,不過都沒有實際的代碼。簡單摸索了一下,寫了個小 Demo 試了試,果然可以。給大家共用一下。
不解釋代碼了,大家看注釋。

 

package com.xxiyy.spl;
 
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
 
public class RecordThread extends Thread {
    private AudioRecord ar;
    private int bs;
    private static int SAMPLE_RATE_IN_HZ = 8000;
    private boolean isRun = false;
 
    public RecordThread() {
        super();
        bs = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
        ar = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT, bs);
    }
 
    public void run() {
        super.run();
        ar.startRecording();
                // 用於讀取的 buffer
        byte[] buffer = new byte[bs];
        isRun = true;
        while (isRun) {
            int r = ar.read(buffer, 0, bs);
            int v = 0;
                        // 將 buffer 內容取出,進行平方和運算
            for (int i = 0; i < buffer.length; i++) {
                // 這裡沒有做運算的最佳化,為了更加清晰的展示代碼
                v += buffer[i] * buffer[i];
            }
            // 平方和除以資料總長度,得到音量大小。可以擷取白色雜訊值,然後對實際採樣進行標準化。
            // 如果想利用這個數值進行操作,建議用 sendMessage 將其拋出,在 Handler 裡進行處理。
            Log.d("spl", String.valueOf(v / (float) r));
        }
        ar.stop();
    }
 
    public void pause() {
                // 在調用本線程的 Activity 的 onPause 裡調用,以便 Activity 暫停時釋放麥克風
        isRun = false;
    }
 
    public void start() {
                // 在調用本線程的 Activity 的 onResume 裡調用,以便 Activity 恢複後繼續擷取麥克風輸入音量
        if (!isRun) {
            super.start();
        }
    }
}

This entry was posted on Monday, November 8th, 2010 at 20:02 and is filed under android. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.