2013-01-17 18 views
0

现在我正在尝试获取iOS中歌曲的长度。如何限制iOS中的float值

- (NSString *)returnofTotalLength 
{ 
    float duration = [[self.player.nowPlayingItem valueForProperty:MPMediaItemPropertyPlaybackDuration] floatValue]/60.0f; 
    NSString *length = [NSString stringWithFormat:@"%.2f",duration];; 
    NSString *totalLength = [length stringByReplacingOccurrencesOfString:@"." withString:@":"]; 

    return totalLength; 
} 

以上代码是歌曲的总长度,如5:90所示。 您知道5:90不能为真,因为60秒是1分钟。

这应该是6:30

所以我要限制1 minute (60 seconds).

该值如何我能做到这一点请大家帮我?

谢谢。

回答

0

我刚刚得到的答案我自己的问题。 感谢您的其他答案。 :)

NSTimeInterval currentProgress = [[self.player.nowPlayingItem valueForProperty:MPMediaItemPropertyPlaybackDuration] floatValue]; 

    float min = floor(currentProgress/60); 
    float sec = round(currentProgress - min * 60); 

    NSString *time = [NSString stringWithFormat:@"%02d:%02d", (int)min, (int)sec]; 
    return time; 

这将返回NSString与完整的格式。

1

这是简单的数学。伪代码:

minutes = (int)(seconds/60); 
rest = seconds % 60; 
result = minutes:rest 

Objc:

int seconds = 150; 
int minutes = (int)(seconds/60); 
int rest  = seconds % 60; 
return [NSString stringWithFormat:@"%i:%i", minutes, rest]; 
+0

你可以显示它在Objective-C? –

+0

刚编辑我的答案。 –

1

做以下操作:

min=(int)duration/60; 
sec=duration%60; 

不是附加分和第二

1

如果你的时间跨越到小时,然后你可以去这样的:

NSInteger seconds = duration % 60; 
NSInteger minutes = (duration/60) % 60; 
NSInteger hours = duration/(60 * 60); 
NSString *result = nil; 

result = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hours, minutes, seconds];