3

I followed the documents about how to set up and observer using KVO mechanism http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html

It's suppose to be very easy.

I created an AVAudioPlayer object and I want to track after every change in it's current time.

I use this code to set up the observer:

[_player addObserver:self forKeyPath:@"currentTime" options:NSKeyValueObservingOptionNew context:NULL];

This code to handle the changes:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"currentTime"]) {
    //Do something
}}

And this code when the audio ends:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
// Remove the observation
[_player removeObserver:self forKeyPath:@"currentTime"];}

For some reason the observer doesn't call to the -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

I know that I can use NSTImer and trigger it when the audio starts playing but I'm looking for smoother way to do this. I also can use AVPlayer object instead and track it by using it's addPeriodicTimeObserverForInterval:queue:usingBlock: But I don't want to lose all the advantages of the AVAudioPlayer object.

What am I doing wrong with the observer? Do you have another suggestion how to use AVAudioPlayer and manage tracking after it's currentTime property?

Thanks in advance,

Amit
  • 205
  • 4
  • 8

3 Answers3

9

You're doing nothing wrong.

I've tried to do this as well and it just doesn't fire.

I had to use an NSTimer instead that polled the currentTime :(

deanWombourne
  • 38,189
  • 13
  • 98
  • 110
  • 6
    Thanks for your response. Eventually, I replaced my player to AVPlayer and used it's addPeriodicTimeObserverForInterval:queue:usingBlock: methode to trace after it's currentTime. – Amit Dec 21 '11 at 11:30
  • Hmm, I might have to do the same in my app; that's a much better solution than my timer hack :) Thanks for the tip! – deanWombourne Dec 21 '11 at 11:32
  • 1
    I used this solution, but only with `CADisplayLink` instead of `NSTimer`, to achieve more consistent refresh rate. – zubko Feb 19 '16 at 11:47
3

KVO will fire for the currentTime property on AVAudioPlayer only when a caller changes the value directly. It will not fire when as the audio clip progresses. To track that, you will have to use NSTimer, as has already been suggested by deanWombourne.

Eric apRhys
  • 316
  • 2
  • 7
0

Have you tried

//KVO [self setValue:[NSNumber numberWithFloat:currentTime] forKey:@"currentTime"];

I did this when currentTime changing,and the KVO work fine.but it's still need a timer to tell setting value =.=

Pengxuan Li
  • 91
  • 1
  • 1
  • 5