Wednesday, June 5, 2013

AVAudioPlayer currentTime example in Objective C (iOS).


AVAudioPlayer currentTime

The playback point, in seconds, within the timeline of the sound associated with the audio player.

@property NSTimeInterval currentTime

Discussion of [AVAudioPlayer currentTime]
If the sound is playing, currentTime is the offset of the current playback position, measured in seconds from the start of the sound. If the sound is not playing, currentTime is the offset of where playing starts upon calling the play method, measured in seconds from the start of the sound.

By setting this property you can seek to a specific point in a sound file or implement audio fast-forward and rewind functions.

AVAudioPlayer currentTime example.
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if ([_player currentTime] != [_player duration] && [_player currentTime] != 0.0f) {
        [_player play];
        return;
    }
...

Example of [AVAudioPlayer currentTime].
- (void) checkPlaybackTime:(NSTimer *)theTimer
{
  float seconds = audioPlayer.currentTime;
  if (seconds => 10.5 && seconds < 11.5) {
    // do something
  } else if (seconds >= 22.5 && seconds < 23.5) {
    // do something else
  }
}

AVAudioPlayer currentTime example.
- (void)safeSetCurentTime:(NSTimeInterval)newTime {
self._player.currentTime = newTime;
if (self._player.currentTime != newTime)
{
    // code falls through to here all the time
            // the second attempt _usually_ works.
    [self prepareAudioForPlayback];
    self._player.currentTime = newTime;
    //NSLog(@"Set time failed");
}
}

End of AVAudioPlayer currentTime example article.