Wednesday, June 5, 2013

AVAudioPlayer duration example in Objective C (iOS).


AVAudioPlayer duration

Returns the total duration, in seconds, of the sound associated with the audio player. (read-only)

@property(readonly) NSTimeInterval duration

AVAudioPlayer duration example.
NSTimeInterval theTimeInterval = audioPlayer.duration;
 // Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];

// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
// Get conversion to hours, minutes, seconds
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];
NSLog(@"%02d:%02d:%02d", [breakdownInfo hour], [breakdownInfo minute], [breakdownInfo second]);
[date1 release];
[date2 release];

Example of [AVAudioPlayer duration].
    // Say you get the duration from AVAudioPlayer *p;
    NSString *dur = [NSString stringWithFormat:@"%02d:%02d", (int)((int)(p.duration)) / 60, (int)((int)(p.duration)) % 60];

AVAudioPlayer duration example.
// Place this where you start to play
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                     target:self
                                                   selector:@selector(updateTimeLeft)
                                                   userInfo:nil
                                                    repeats:YES];
And create the method to update you UI:

- (void)updateTimeLeft {
    NSTimeInterval timeLeft = self.player.duration - self.player.currentTime;

    // update your UI with timeLeft
    self.timeLeftLabel.text = [NSString stringWithFormat:@"%f seconds left", timeLeft];
}

End of AVAudioPlayer duration example article.