Wednesday, June 5, 2013

AVAudioPlayer numberOfChannels example in Objective C (iOS).


AVAudioPlayer numberOfChannels

The number of audio channels in the sound associated with the audio player. (read-only)

@property(readonly) NSUInteger numberOfChannels

AVAudioPlayer numberOfChannels example.
fileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@" Om Namo" ofType:@"aac"]];
self._player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
if (self._player)
{
_fileName.text = [NSString stringWithFormat: @"%@ (%d ch.)", [[self._player.url relativePath] lastPathComponent], self._player.numberOfChannels, nil];
[self updateViewForPlayerInfo];
[self updateViewForPlayerState];
}

[fileURL release];

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

if (!playerTimer)
{
    playerTimer = [NSTimer scheduledTimerWithTimeInterval:0.001
                  target:self selector:@selector(monitorAudioPlayer)
                userInfo:nil
                 repeats:YES];
}

[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 numberOfChannels example.
-(void)monitorAudioPlayer{

    [audioPlayer updateMeters];

    for (int i=0; i<audioPlayer.numberOfChannels; i++)
    {       
        float power = [ audioPlayer averagePowerForChannel: i ];
        float peak = [ audioPlayer peakPowerForChannel: i ];
}
}

End of AVAudioPlayer numberOfChannels example article.