Search code examples
iphoneobjective-ciosavaudioplayernstimer

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.


Solution

  • 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