Detecting blowing on the iPhone microphone?

前端 未结 5 2101
再見小時候
再見小時候 2020-12-23 19:01

I am trying to detect when the user is blowing into the mic of an iPhone. Right now I am using the SCListener class from Stephen Celis to call

if ([[SCListen         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 19:52

    Try this It is working fine for me. Thanks @jinhua liao

    - (void)viewDidLoad {
       [super viewDidLoad];
    
    lowPassResults = 0.0;
    [self readyToBlow1];
    
    NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
    
    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
                              [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                              [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                              [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                              nil];
    
    NSError *error;
    
    recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
    
    if (recorder) {
        [recorder prepareToRecord];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
        recorder.meteringEnabled = YES;
        [recorder record];
        levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 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 peakPowerForChannel:0]));
    lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;  
    NSLog(@"lowpassResult is %f",lowPassResults);
    if (lowPassResults > 0.95){
        NSLog(@"Mic blow detected");
        [levelTimer invalidate];
    }
    }
    

提交回复
热议问题