Search code examples
avfoundationcore-audioios8xcode6beta

Can't Get Microphone Sound Level


I ve tried to get microphone volume level like this: in header file:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>

@interface AlarmViewController : UIViewController {
    AVAudioRecorder *recorder;
    NSTimer *levelTimer;
}

@property (strong, nonatomic) IBOutlet UISegmentedControl *segmentedControl;
@property (strong, nonatomic) IBOutlet UILabel *timeLabel;

- (void)timeChange:(NSTimer *)timer;
- (void)levelTimerCallback:(NSTimer *)timer;

@end

in implementation 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:0.5 target:self selector:@selector(levelTimerCallback:) userInfo:nil repeats:YES];
    }
    else {
        NSLog(@"%@", [error description]);
    }
}

- (void)levelTimerCallback:(NSTimer *)timer {
    [recorder updateMeters];
    NSLog(@"Average input: %f Peak input: %f", [recorder averagePowerForChannel:0], [recorder peakPowerForChannel:0]);
}

So, in log it returns the following:

2014-06-29 16:31:42.400 NightLight[1140:388914] Average input: -120.000000 Peak input: -120.000000

I don't know what should I do? I'm sure it's allowed to use microphone in iPhone's privacy settings.


Solution

  • It turns out that you need to employ AVAudioSession to set context to the app. Add following code in - (void)viewDidLoad after [super viewDidLoad];

    // Set audio context to app
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];