2010-08-26 99 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