这是Unity 3D游戏引擎的代码...
我尝试使用此源脚本监控声音分贝,但为什么我得到负分贝?
理论上,正常对话的声音会产生60db,即使是安静的房间也会产生 10-20dB ...
任何想法 ?
分贝计算结果:
以下是源代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VR_SoundMonitor : MonoBehaviour
{
public float DecibleValue;
public float RmsValue;
public float PitchValue;
private AudioSource audioSourceObject;
private float[] _spectrum;
private float[] _samples;
private float _fSample;
const int QSamples = 1024;
const float RefValue = 0.1f;
const float Threshold = 0.02f;
void Start ()
{
audioSourceObject = GetComponent<AudioSource> ();
InitVariable ();
InitMicrophone ();
}
//Nyalakan Microphone
private void InitMicrophone()
{
audioSourceObject.clip = Microphone.Start ("SoundMonitoring", false, 60, 44100);
while (!(Microphone.GetPosition(null) > 0)) { }
audioSourceObject.Play();
}
private void InitVariable()
{
_samples = new float[QSamples]; //use constanta (3 below)
_spectrum = new float[QSamples];
_fSample = AudioSettings.outputSampleRate;
}
void Update ()
{
CalculateAnalyzeSound (audioSourceObject);
Debug.Log ("Decibels="+DecibleValue+" ## RmsVal="+RmsValue);
}
public void CalculateAnalyzeSound(AudioSource audio)
{
float _RmsValue;
float _DbValue;
float _PitchValue;
audio.GetOutputData(_samples, 0);
int i = 0;
float sum = 0;
for (i = 0; i < QSamples; i++)
{
sum += _samples[i] * _samples[i]; // sum squared samples
}
_RmsValue = Mathf.Sqrt(sum / QSamples); // rms = square root of average
_DbValue = 20 * Mathf.Log10(_RmsValue / RefValue); // calculate dB
if (_DbValue < -160) _DbValue = -160; // clamp it to -160dB min
RmsValue = _RmsValue;
DecibleValue = _DbValue;
}
}
怎么了 ?有什么想法,请告诉我......