2010-08-26 36 views
4

我有一个简单的MP3播放通过AVAudioPlayer,我想能够显示剩下多少时间。AVAudioPlayer时间显示

我知道答案包括从AVAudioPlayer.currentTime减去AVAudioPlayer.duration,但我不知道如何实现一个函数,它在播放时计算它(就像我猜的Actionscript中的onEnterFrame)。目前currentTime是静态的,即零。

回答

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]; 
} 
+0

谢谢VFN,它看起来像完美的解决方案只有一个问题,我发现:定时器没有被解雇! – daidai 2010-08-26 02:48:17

+2

啊耶只需要使用'scheduledTimerWithTimeInterval'而不是'timerWithTimeInterval' – daidai 2010-08-26 03:08:45

+0

是的,你需要启动它或使用预定的方法。现在编辑! – vfn 2010-08-26 03:16:00