我想測量周圍的音量,如果我做的是正確的話,我不太確定。我是否正確地將分貝從-120 - 0轉換爲0 - 120
我想創建一個範圍爲0(安靜)到120(非常嘈雜)的VU表。
我獲得了峯值和平均功率,但在正常安靜的環境中非常高。 請給我一些指針。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//creating an audio CAF file in the temporary directory, this isn’t ideal but it’s the only way to get this class functioning (the temporary directory is erased once the app quits). Here we also specifying a sample rate of 44.1kHz (which is capable of representing 22 kHz of sound frequencies according to the Nyquist theorem), and 1 channel (we do not need stereo to measure noise).
NSDictionary* recorderSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
[NSNumber numberWithInt:44100],AVSampleRateKey,
[NSNumber numberWithInt:1],AVNumberOfChannelsKey,
[NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
nil];
NSError* error;
NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&error];
//enable measuring
//tell the recorder to start recording:
[recorder record];
if (recorder) {
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.01 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
} else
{
NSLog(@"%@",[error description]);
}
}
- (void)levelTimerCallback:(NSTimer *)timer {
[recorder updateMeters];
const double ALPHA = 0.05;
double peakPowerForChannel = pow(10, (0.05 * [recorder averagePowerForChannel:0]));
lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
NSLog(@"Average input: %f Peak input: %f Low pass results: %f", [recorder averagePowerForChannel:0], [recorder peakPowerForChannel:0], lowPassResults);
float tavgPow =[recorder averagePowerForChannel:0] + 120.0;
float tpPow = [recorder peakPowerForChannel:0] + 120.0;
float avgPow = tavgPow;//(float)abs([recorder averagePowerForChannel:0]);
float pPow = tpPow;//(float)abs([recorder peakPowerForChannel:0]);
NSString *tempAvg = [NSString stringWithFormat:@"%0.2f",avgPow];
NSString *temppeak = [NSString stringWithFormat:@"%0.2f",pPow];
[avg setText:tempAvg];
[peak setText:temppeak];
NSLog(@"Average input: %f Peak input: %f Low pass results: %f", avgPow,pPow , lowPassResults);
}
嗨邁克爾,感謝您的回覆。 我相信平均PowerForChannel是-x 將要轉換爲0 - 120值的分貝值 – Desmond 2012-02-12 08:50:05
@Desmond:好的,我建議更改peakPowerForChannel以直接使用分貝值的最後一步。您稍後再添加120。你還需要通過使用max(0,db)來確保它不小於零,就像我對'db = db <0'所做的一樣。 0:db;' – 2012-02-12 09:20:07
感謝邁克爾,然而分貝在一個安靜的房間裏非常高......我下載了一個decibel10應用程序來檢查它的分貝不同是巨大的。該應用程序顯示約40db,我的顯示70db。 我的主要目標是檢查用戶是否在發出噪音。如果超過閾值就會觸發一些事情。 – Desmond 2012-02-12 09:39:12