Search code examples
avaudioplayeraudio-recordingavaudiorecorderavaudiosession

ios , get float level mic updateMesters when mic is recording audio


here is my code for recording now how can get the level sound input in mic by sample UIlable float number

i think i will use this function but how can i use this in rec.h & rec.m file

(void)updateMeters

AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
recordedTmpName = [[NSString alloc] initWithFormat:@"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"aac"];
temporaryRecFile= [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:recordedTmpName]];
recorder = [[ AVAudioRecorder alloc] initWithURL:temporaryRecFile settings:recordSetting error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];

Solution

  • During recording, you have to call updateMeters periodically, and get the average power by - (float)averagePowerForChannel:(NSUInteger)channelNumber

    [recorder setDelegate:self];
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;
    [recorder record];
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
    
    
    
    
    - (void) handleTimer
    {
        [recorder updateMeters];
        label.text = [NSString stringWithFormat:@"lf",[recorder averagePowerForChannel:0]];
    }
    

    To see more information, you can visit AVAudioRecorder Class Reference