views:

37

answers:

1

I have a simple mp3 playing through AVAudioPlayer and I want to be able to display how much time is left.

I know the answer includes subtracting AVAudioPlayer.duration from AVAudioPlayer.currentTime but I don't know how to implement a function which calculates it while it's playing (like an onEnterFrame in Actionscript I guess). At present currentTime is static, i.e. zero.

+1  A: 

I would go for an NSTimer. Schedule it to run every second while the media is played and so you can keep your UI updated with the time left.

// Place this where you start to play
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                     target:self
                                                   selector:@selector(updateTimeLeft)
                                                   userInfo:nil
                                                    repeats:YES];

And create the method to update you 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];
}
vfn
Thank you vfn, it looks like the perfect solution only one problem I've found: The timer is not firing!
daidai
Ah yep just needed to use `scheduledTimerWithTimeInterval` instead of `timerWithTimeInterval`
daidai
Yeah, you would need to fire it or to use the scheduled method. It's edited now!
vfn