Wednesday, June 5, 2013

AVAudioPlayer averagePowerForChannel example in Objective C (iOS).


AVAudioPlayer averagePowerForChannel

Returns the average power for a given channel, in decibels, for the sound being played.

- (float)averagePowerForChannel:(NSUInteger)channelNumber

Parameters
channelNumber
The audio channel whose average power value you want to obtain. Channel numbers are zero-indexed. A monaural signal, or the left channel of a stereo signal, has channel number 0.

Return Value
A floating-point representation, in decibels, of a given audio channel’s current average power. A return value of 0 dB indicates full scale, or maximum power; a return value of -160 dB indicates minimum power (that is, near silence).

If the signal provided to the audio player exceeds ±full scale, then the return value may exceed 0 (that is, it may enter the positive range).

Discussion of [AVAudioPlayer averagePowerForChannel]
To obtain a current average power value, you must call the updateMeters method before calling this method.

AVAudioPlayer averagePowerForChannel example.
for (int currChan = 0; currChan < channels; currChan++) {
    //Log the peak and average power
    NSLog(@"%d %0.2f %0.2f", currChan, [audioPlayer peakPowerForChannel:currChan], [audioPlayer averagePowerForChannel:currChan]);
}

Example of [AVAudioPlayer averagePowerForChannel].
-(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 averagePowerForChannel example.
 have used the AVAudioPlayer's peakPowerForChannel and averagePowerForChannel method for getting the decibles

  AVAudioPlayer *avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];
    avPlayer.delegate = self;

    avPlayer.meteringEnabled = YES;
     [avPlayer prepareToPlay];
     [avPlayer play];

 NSTimer *levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
This method is return the peakPowerForChannel and averagePowerForChannel

- (void)levelTimerCallback:(NSTimer *)timer {

    [avPlayer updateMeters];
    NSLog(@"Peak left: %f Avg right: %f", [avPlayer peakPowerForChannel:0],[avPlayer averagePowerForChannel:0]);

}

End of AVAudioPlayer averagePowerForChannel example article.