2
votes

I use a AVAudioPlayer to play a MP3 file. While the player is running I would like to control a slideshow with the current time of the player. Of course I could do this with a NSTimer which is fired when the play starts but that doesn't sound like a sweet solution. How can I ad a observer to the currentTime Value of the AVAudioPlayer?

Thanks, Philip

1

1 Answers

0
votes

The cleanest way to do this is to set up a audio player yourself using AVPlayer and set up a time-passed observation using -[AVPlayer addBoundaryTimeObserverForTimes:queue:usingBlock:].


If you’re stuck with the AVAudioPlayer I believe you can use Key-Value Observing to listen for the currentTime change:

static NSString *someObservationContext = @"something";

[audioPlayer addObserver:self forKeyPath:@"currentTime" options:0 context:&someObservationContext];

and then implement

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == &someObservationContext) {
        NSTimeInterval t = [(AVAudioPlayer *)object currentTime];
        // do your thing
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }

Be sure to call -[NSObject removeObserver:forKeyPath:] to remove the observation hook before you tear down the AVAudioPlayer.