Saqib bhatti
Saqib bhatti

Reputation: 11

Microphone code doesn't run on iPhone device

I am trying to run the following code on my device with no success. Although the code works perfectly on Simulator. I have been following this tutorial. It simply crash on device.

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

Code is:

@interface MicBlowViewController : UIViewController {
    AVAudioRecorder *recorder;
    NSTimer *levelTimer;
    double lowPassResults;
}
- (void)levelTimerCallback:(NSTimer *)timer;
@end

.m file :

- (void)viewDidLoad {
    [super viewDidLoad];
    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: 3 
                                                      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;  
    if (lowPassResults < 0.95)
        NSLog(@"Mic blow detected");
}

Upvotes: 0

Views: 417

Answers (1)

bpolat
bpolat

Reputation: 3908

Add those two lines of code after [recorder prepareToRecord ]

    [recorder prepareToRecord];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];

Upvotes: 1

Related Questions