2011-05-19 39 views
3

我有一個倒數計時器,顯示音軌上剩餘的秒數。由於某些原因,倒計時不會以1秒的間隔計算,但第一次計數爲2秒,下一次計數則爲1秒。 (它在這種模式下計算 - 它跳過2秒,然後是1遍)。AVAudioPlayer - 在UILabel上顯示倒數計時器

這裏是我的代碼:

// 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]; 

} 

,這裏是我的NSTimer:

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

感謝您的幫助。

回答

7

試試這個

- (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]; 
} 

只是一個想法

+0

謝謝。我得到一個無效操作數對二進制模數%。我讀過%運算符不適用於浮點值。 – hanumanDev 2011-05-19 12:05:58

+0

概念除以60分鐘並以60爲單位模數 – 2011-05-19 12:08:08

+0

這就是我最終使用的模數運算。 \t \t int sec = lroundf(timeLeft)%60; – hanumanDev 2011-05-19 13:30:26

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

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

嘗試這樣的...它只會顯示在幾秒鐘內

+0

感謝您的回覆。我之前試過這個代碼。它以300.0000秒的格式顯示時間。我需要它像5:30(5分30秒)格式。 – hanumanDev 2011-05-19 11:51:27

0

最佳方式使用系統甲:

- (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; 
    }