hanumanDev
hanumanDev

Reputation: 6614

AVAudioPlayer - Displaying a countdown timer on a UILabel

I have a countdown timer that displays the number of seconds left on a audio track. For some reason the countdown is not counting at 1 second intervals, but 2 seconds on the first count and then 1 second on the next count. (It's counting in this pattern - it jumps 2 seconds, then 1 over and over).

here's my code:

// display current time left on the track
- (void)updateTimeLeft {
    NSTimeInterval timeLeft = self.player.duration - self.player.currentTime;

    // update your UI with timeLeft
    self.timeDisplay.text = [NSString stringWithFormat:@"%.2f", timeLeft / 60];

}

and here's my NSTimer:

NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimeLeft) userInfo:nil repeats:YES];

thanks for any help.

Upvotes: 3

Views: 3397

Answers (3)

Ofir Malachi
Ofir Malachi

Reputation: 1286

Best way using system formate:

    - (NSString*)updateTimeLeft
    {
        float current = CMTimeGetSeconds(_player.currentItem.currentTime);
        float duration = CMTimeGetSeconds(_player.currentItem.duration);

        if(!isnan(current) && !isnan(duration)){
             NSTimeInterval timeLeft = duration - current;    
             NSTimeInterval durationInSeconds = timeLeft;
             NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
             formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitSecond;
             formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
             NSString *string = [formatter stringFromTimeInterval:durationInSeconds];

             return string;
         }

     return nil;
    }

Upvotes: 0

Narayanan Ramamoorthy
Narayanan Ramamoorthy

Reputation: 826

try this

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

int min=timeLeft/60;

int sec = lroundf(timeLeft) % 60;

// update your UI with timeLeft
self. timeDisplay.text = [NSString stringWithFormat:@"%d minutes %d seconds", min,sec];
}

just an idea

Upvotes: 7

Narayanan Ramamoorthy
Narayanan Ramamoorthy

Reputation: 826

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

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

try like this...it will display only in seconds

Upvotes: 1

Related Questions