我有一个简单的mp3通过AVAudioPlayer播放,我希望能够显示剩下多少时间。
我知道答案包括从AVAudioPlayer.duration
中减去AVAudioPlayer.currentTime
但我不知道如何实现在播放时计算它的函数(就像我猜测的那样在ActionScript中的onEnterFrame)。目前currentTime
是静态的,即零。
答案 0 :(得分:12)
我会选择NSTimer。安排它在播放媒体时每秒运行一次,这样您就可以在剩下的时间内更新UI。
// Place this where you start to play
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(updateTimeLeft)
userInfo:nil
repeats:YES];
并创建更新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];
}
答案 1 :(得分:1)
我迅速使用它并起作用:
// this for show remain time
let duration = Int((player1?.duration - (player1?.currentTime))!)
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
durLabel.text = NSString(format: "%02d:%02d", minutes2,seconds2) as String
//this for current time
let currentTime1 = Int((player1?.currentTime)!)
let minutes = currentTime1/60
let seconds = currentTime1 - minutes * 60
curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String