ios – AVPlayer项缓冲区为空

我使用播放流内容的AVPlayer.我想知道缓冲区空的时间和准备播放的时间.但观察者“playbackBufferEmpty”和“playbackLikelyToKeepUp”在每次需要时都不起作用.他们有时工作但往往不工作.我在OSX 10.7.5下只使用iPad模拟器iOS 6.1.

以下是我设置和观察观察者的方式:

- (void)playAudioStream:(NSURL *)audioStreamURL
{
 if(_audioPlayer && _audioPlayer.currentItem)
 {
     [_audioPlayer removeObserver:self forKeyPath:StatusKey];
     [_audioPlayer.currentItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
     [_audioPlayer.currentItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
 }

 AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:audioStreamURL];

 [playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
 [playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];

 _audioPlayer = [AVPlayer playerWithPlayerItem:playerItem];

 [_audioPlayer addObserver:self forKeyPath:StatusKey options:NSKeyValueObservingOptionNew context:nil];

 //[_audioPlayer replaceCurrentItemWithPlayerItem:playerItem];
 //_audioPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
 [_audioPlayer play];
}
...

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
 if ([keyPath isEqualToString:@"playbackBufferEmpty"] )
 {
    if (_audioPlayer.currentItem.playbackBufferEmpty)
    {
       ...
    }

 }

 if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"])
 {
    if (_audioPlayer.currentItem.playbackLikelyToKeepUp)
    {
        ...
    }
 }
}

请帮助我获得“缓冲区空”和“缓冲区就绪”事件的正确方法(例如,当Internet连接断开时).谢谢!

最佳答案 添加观察者时需要使用上下文.这是您的示例代码.

初始化背景

static void *playbackLikelyToKeepUpKVOToken = &playbackLikelyToKeepUpKVOToken;
static void *playbackBufferEmpty = &playbackBufferEmpty;
static void *playbackBufferFull = &playbackBufferFull;

添加观察者

[self.playerItem removeObserver:self forKeyPath:@"playbackBufferEmpty" context:playbackBufferEmpty];
[self.playerItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp" context:playbackLikelyToKeepUpKVOToken];
[self.playerItem removeObserver:self forKeyPath:@"playbackBufferFull" context:playbackBufferFull];

处理

if (context == playbackLikelyToKeepUpKVOToken)
{
    if (self.playerItem.playbackLikelyToKeepUp)
    {
        NSLog(@"recieve playbackLikelyToKeepUp");
    }

}
else if (context == playbackBufferEmpty)
{
    if (self.playerItem.playbackBufferEmpty)
    {
        NSLog(@"recieve playbackBufferEmpty");
    }
}
else if(context == playbackBufferFull)
{
    NSLog(@"recieve playbackBufferFull");
}
else
{
    [super observeValueForKeyPath:path ofObject:object change:change context:context];
}
点赞