在Android中获取麦克风声音水平(分贝级别)

7

我对Android不是很了解,已经搜索了相当长一段时间。我想构建一个类似于分贝计的应用程序,实时显示声音水平。如果房间里有噪音,会有某些指示,如果很安静,也会有某些指示。

我完全不知道如何做到这一点。能否有人解释一下麦克风声音级别应用程序的基础知识?如果可能的话,请提供一些代码。

谢谢!

3个回答

9
您可以使用 MediaRecorder.getMaxAmplitude() 方法。
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {

    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO},
            RECORD_AUDIO);
}
  1. Get the noise level using the MediaRecorder,

    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mRecorder.setOutputFile("/dev/null");
    try {
        mRecorder.prepare();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mRecorder.start();
    
  2. Start the MediaRecorder,

    private Runnable mSleepTask = new Runnable() {
        public void run() {
            //Log.i("Noise", "runnable mSleepTask");
            mSensor.start();
            if (!mWakeLock.isHeld()) {
                 mWakeLock.acquire();
            }
            //Noise monitoring start
            // Runnable(mPollTask) will execute after POLL_INTERVAL
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);
        }
    };
    
  3. Create Runnable Thread to check the noise level frequently,

    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = mSensor.getAmplitude();
            //Log.i("Noise", "runnable mPollTask");
            // Runnable(mPollTask) will again execute after POLL_INTERVAL
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);
        }
    };
    

使用以下公式将振幅转换为分贝:

return 20 * Math.log10(mRecorder.getMaxAmplitude() / 2700.0);
  1. Monitoring the Voice and Alert for the Louder Noise.

    // Create runnable thread to Monitor Voice
    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = mSensor.getAmplitude();
            //Log.i("Noise", "runnable mPollTask");
            updateDisplay("Monitoring Voice...", amp);
    
            if ((amp > mThreshold)) {
                callForHelp(amp);
                //Log.i("Noise", "==== onCreate ===");
            }
            // Runnable(mPollTask) will again execute after POLL_INTERVAL
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);
        }
    };
    

@AshwinBalani 你可以在这里查看 https://github.com/Santosh-Gupta/SitcomSimulator/blob/master/noisealert/src/com/androidexample/noisealert/NoiseAlert.java - Tung Duong

1

0

5
这不是答案,这位先生明显在问如何构建应用程序,而不是寻找应用程序。 - chntgomez
1
@chntgomez 我认为timemirror给出了应用程序示例,因为链接中有代码,所以可以分析它并学习如何做(虽然不像这里的代码那么直接)。 - Edw590

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接