19

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 ([[SCListener sharedListener] peakPower] > 0.99)

in an NSTimer. However, this returns true sometimes when I'm not blowing. Anyone have any sample code to check if the user is blowing into the mic?

2
  • 4
    Maybe the wind is blowing. :) Sorry, this question made me laugh.
    – JP Alioto
    Apr 28, 2009 at 2:11
  • Hah, nah. Even when I would be inside, simply tapping on the screen would cause the function to trigger
    – Joe
    Apr 28, 2009 at 3:39

5 Answers 5

25

I would recommend low-pass filtering the power signal first. There is always going to be some amount of transient noise that will mess with instantaneous readings; low-pass filtering helps mitigate that. A nice and easy low-pass filter would be something like this:

// Make this a global variable, or a member of your class:
double micPower = 0.0;
// Tweak this value to your liking (must be between 0 and 1)
const double ALPHA = 0.05;

// Do this every 'tick' of your application (e.g. every 1/30 of a second)
double instantaneousPower = [[SCListener sharedListener] peakPower];

// This is the key line in computing the low-pass filtered value
micPower = ALPHA * instantaneousPower + (1.0 - ALPHA) * micPower;

if(micPower > THRESHOLD)  // 0.99, in your example
    // User is blowing on the microphone
1
  • can you stop recording if volume levels get over the threshold as well? meaning if have a voip app, and dont want a firetruck siren to roar over the conversation can i pause the mic once the threshold is surpassed?
    – owen gerig
    Dec 12, 2011 at 17:56
13

when run on iPhone, you should add the following code after [recorder prepareToRecorder]

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
1
  • 2
    I was looking for this information for 3 hours. It works now!.
    – bpolat
    Sep 9, 2014 at 21:47
11

Use return as lowPassResults is bigger than 0.55. This is working fine:

-(void)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];
        recorder.meteringEnabled = YES;
        [recorder record];
        levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.01 target: self selector: @selector(levelTimerCallback1:) userInfo: nil repeats: YES];
    } else
        NSLog(@"%@",[error description]);
}

-(void)levelTimerCallback1:(NSTimer *)timer { [recorder updateMeters];
    const double ALPHA = 0.05; 
    double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0])); 
    double lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults; 
    if (lowPassResults > 0.55) { 
        lowPassResults = 0.0;
        [self invalidateTimers];
        NextPhase *objNextView =[[NextPhase alloc]init];
        [UIView transitionFromView:self.view
                      toView:objNextView.view
                      duration:2.0
                      options:UIViewAnimationOptionTransitionCurlUp
                      completion:^(BOOL finished) {}
        ];
        [self.navigationController pushViewController:objNextView animated:NO];
    **return;**
    }
}
4
  • now u can see lowPassResults. It was just misaligned. sorry :) Feb 25, 2013 at 4:45
  • I get a compiler error for lowPassResults, since it's being used for the equation that initializes it. Is lowPassResults supposed to be initialized somewhere else?
    – bmueller
    May 31, 2013 at 21:03
  • Yes you have to initialize lowPassresults either in viewDidLoad or viewWillAppear as you required. just initialize as lowPassResults = 0.0; Jun 3, 2013 at 7:30
  • Can someone explain the "low pass filter" in this code. As I understand a low pass filter, you would exclude high frequency sounds from your measurements. Yet nothing here addresses sound frequency. peakPowerforChannel returns the sound volume in decibels. And the code merely manipulates that value. What am I missing?
    – lp1756
    Aug 12, 2013 at 19:13
4

http://mobileorchard.com/tutorial-detecting-when-a-user-blows-into-the-mic/

this tutorial works fine with simulator but its not working in iphone there is no response from iphone mic

2

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];
}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy