我正在使用 EZAudio 构建一个 iOS 应用程序。它的委托返回一个float**
缓冲区,其中包含指示检测到的音量的浮点值。这个委托被不断地调用,它的工作在不同的线程中完成。
我要做的是从 EZAudio 获取浮点值并将其转换为分贝。
EZAudioDelegate
- (void)microphone:(EZMicrophone *)microphone hasAudioReceived:(float **)buffer withBufferSize:(UInt32)bufferSize withNumberOfChannels:(UInt32)numberOfChannels {
/*
* Returns a float array called buffer that contains the stereo signal data
* buffer[0] is the left audio channel
* buffer[1] is the right audio channel
*/
// Using a separate audio thread to not block the main UI thread
dispatch_async(dispatch_get_main_queue(), ^{
float decibels = [self getDecibelsFromVolume:buffer withBufferSize:bufferSize];
NSLog(@"Decibels: %f", decibels);
});
}
问题
问题是,在通过以下链接实施解决方案后,我不明白它是如何工作的。如果有人能解释它如何将音量转换为分贝,我将不胜感激
编码
该解决方案使用Accelerate Framework中的以下方法将音量转换为分贝:
下面是getDecibelsFromVolume
从 EZAudio Delegate 调用的方法。它是从委托中传递float** buffer
过来的。bufferSize
- (float)getDecibelsFromVolume:(float**)buffer withBufferSize:(UInt32)bufferSize {
// Decibel Calculation.
float one = 1.0;
float meanVal = 0.0;
float tiny = 0.1;
float lastdbValue = 0.0;
vDSP_vsq(buffer[0], 1, buffer[0], 1, bufferSize);
vDSP_meanv(buffer[0], 1, &meanVal, bufferSize);
vDSP_vdbcon(&meanVal, 1, &one, &meanVal, 1, 1, 0);
// Exponential moving average to dB level to only get continous sounds.
float currentdb = 1.0 - (fabs(meanVal) / 100);
if (lastdbValue == INFINITY || lastdbValue == -INFINITY || isnan(lastdbValue)) {
lastdbValue = 0.0;
}
float dbValue = ((1.0 - tiny) * lastdbValue) + tiny * currentdb;
lastdbValue = dbValue;
return dbValue;
}