试试这个代码来启动声音监控:
#pragma mark - AudioStuff
double lowPassResultAudio;
-(void) initAudioRecorder {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setDelegate: self];
NSError *audioSessionError;
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&audioSessionError];
[[AVAudioSession sharedInstance] setActive: YES error: &audioSessionError];
NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
// We can use kAudioFormatAppleIMA4 (4:1 compression) or kAudioFormatLinearPCM for nocompression
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
// We can use 44100, 32000, 24000, 16000 or 12000 depending on sound quality
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
// We can use 2(if using additional h/w) or 1 (iPhone only has one microphone)
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
//initiate recorder
inputAudioUrl = [NSURL fileURLWithPath:pathToFile];
recorder = [[AVAudioRecorder alloc] initWithURL:inputAudioUrl settings:recordSetting error:&error];
if(recorder){
//setting to speaker for appropritae recording
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof (audioRouteOverride),&audioRouteOverride);
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
//for monitoring with same recorder
[recorder record];
[[NSTimer alloc] initWithFireDate:[NSDate date] interval:0.1 target:self selector:@selector(monitorAudioController:) userInfo:,mil repeats:YES]
} else
NSLog(@"%@",[error description]);
}
现在,如果声音值超过限制,即正在播放一些附近的声音,则删除您的视图。
//monitor audion with same recorder
-(void) monitorAudioController: (NSTimer *) timer {
[recorder updateMeters];
const double ALPHA = 0.05;
double peakPowerForChannel_ = pow(10, (ALPHA * [recorder peakPowerForChannel:0]));
// double lowpassMultiplier = (lowPassResultAudio > 0.2f) ? 0.2f : lowPassResultAudio;
double AUDIOMONITOR_THRESHOLD = 0.7;
lowPassResultAudio = ALPHA * peakPowerForChannel_ + (1.0 - ALPHA) * AUDIOMONITOR_THRESHOLD;
// NSLog(@"peakPowerForChannel_=%lf, lowpassMultiplier = %lf, lowPassResultAudio = %lf", peakPowerForChannel_, AUDIOMONITOR_THRESHOLD, lowPassResultAudio);
if (lowPassResultAudio >= AUDIOMONITOR_THRESHOLD) {
//remove here
//invalidate timer
//stop recorder monitoring
}
}