Wednesday, June 5, 2013

AVAudioPlayer meteringEnabled example in Objective C (iOS).

AVAudioPlayer meteringEnabled

A Boolean value that specifies the audio-level metering on/off state for the audio player.

@property(getter=isMeteringEnabled) BOOL meteringEnabled

Discussion of [AVAudioPlayer meteringEnabled]
The default value for the meteringEnabled property is off (Boolean NO). Before using metering for an audio player, you need to enable it by setting this property to YES. If player is an audio player instance variable of your controller class, you enable metering as shown here:

[self.player setMeteringEnabled: YES];

AVAudioPlayer meteringEnabled example.
Set up the recorder once (this part of your code is fine)

[recorder prepareToRecord];
recorder.meteringEnabled = YES;
//Start the actual Recording
[recorder record];

NSTimer *TimerUpdate = [NSTimer scheduledTimerWithTimeInterval:.1
   target:self selector:@selector(timerTask) userInfo:nil repeats:YES];
Then define this small routine to get the peak level:

- (void) timerTask {
   [recorder updateMeters];
   float level = [recorder peakPowerForChannel:0];
   NSLog(@"%f", level);

Example of [AVAudioPlayer meteringEnabled].
audioPlayer.meteringEnabled = YES;
audioPlayer.delegate = self;

if (!playerTimer)
    playerTimer = [NSTimer scheduledTimerWithTimeInterval:0.001
                  target:self selector:@selector(monitorAudioPlayer)

[audioPlayer play];
Add this two methods to your class:

-(void) monitorAudioPlayer
    [audioPlayer updateMeters];
    for (int i=0; i<audioPlayer.numberOfChannels; i++)
        //Log the peak and average power
         NSLog(@"%d %0.2f %0.2f", i, [audioPlayer peakPowerForChannel:i],[audioPlayer averagePowerForChannel:i]);

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
    NSLog (@"audioPlayerDidFinishPlaying:");
    [playerTimer invalidate];
    playerTimer = nil;

AVAudioPlayer meteringEnabled example.
playerAV = [[AVAudioPlayer alloc] initWithContentsOfURL:outURL error:nil];
        playerAV.delegate = self;
        playerAV.meteringEnabled = YES;
        [playerAV prepareToPlay];
        [playerAV play];

End of AVAudioPlayer meteringEnabled example article.