【发布时间】:2025-11-26 10:45:02
【问题描述】:
如题,有人知道原因吗?
请注意,它不会在 iOS 11 上发生。
我的调试环境:
- Xcode 9.2
- iOS 9、10、11
我的代码:
在我的应用程序中,我正在尝试通过 AVFoundation 框架播放流媒体内容。显示视频的长度和当前播放时间也是一项功能。loadVideo 方法在 IBAction 中由于点击按钮而被调用。
另外,observeValueForKeyPath 方法中没有特殊代码来接收 KVO 的事件。
详情如下:
- (void)loadVideo
{
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:VIDEO_URL]];
Float64 duration = CMTimeGetSeconds(item.asset.duration);
[self updateTimeLabel:0.0 duration:duration];
self.player = [[AVPlayer alloc] initWithPlayerItem:item];
AVPlayerLayer *layer = (AVPlayerLayer *)self.playerView.layer;
[layer setPlayer:self.player];
[self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
__weak ViewController *weakSelf = self;
self.token = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(0.1, NSEC_PER_SEC)
queue:nil
usingBlock:^(CMTime time) {
Float64 currentTime = CMTimeGetSeconds(time);
[weakSelf updateTimeLabel:currentTime duration:duration];
}];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"status"]) {
AVPlayer *player = (AVPlayer *)object;
switch (player.status) {
case AVPlayerStatusReadyToPlay:
{
NSLog(@"player's status changed to AVPlayerStatusReadyToPlay");
}
break;
default:
NSLog(@"player's status changed");
break;
}
[player removeObserver:self forKeyPath:@"status"];
}
}
【问题讨论】:
标签: ios objective-c avplayer status key-value-observing