是否有可能通过使用观察者来跟踪AVAudioPlayer对象?

我遵循了关于如何使用KVO机制设置和观察者的文档http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html

这是非常简单的。

我创build了一个AVAudioPlayer对象,我想跟踪当前时间的每一个变化。

我使用这个代码来设置观察者:

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

这个代码来处理更改:

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

而这段代码在audio结束时:

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

由于某些原因,观察者不会调用-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

我知道我可以使用NSTImer,并在audio开始播放时触发它,但我正在寻找更平滑的方式来做到这一点。 我也可以使用AVPlayer对象,并使用它的addPeriodicTimeObserverForInterval:queue:usingBlock:来跟踪它addPeriodicTimeObserverForInterval:queue:usingBlock:但我不想失去AVAudioPlayer对象的所有优点。

我在做什么观察员错了? 你有另一个build议如何使用AVAudioPlayer和pipe理它的currentTime属性后跟踪?

提前致谢,

你没有做错什么。

我也试图做到这一点,它只是不开火。

我不得不使用NSTimer而不是调查currentTime 🙁

只有当调用者直接更改值时,KVO才会触发AVAudioPlayer上的currentTime属性。 随着audio剪辑的进行,它不会启动。 为了跟踪这一点,你必须使用NSTimer,正如deanWombourne所build议的那样。

你有没有尝试过

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

当currentTime改变时,我做了这个,KVO工作正常,但它仍然需要一个定时器来告诉设置值=。=