【问题标题】:AVPlayer with AVPlayerLayer 'ready to play' status no work for the real videoView display具有 AVPlayerLayer“准备播放”状态的 AVPlayer 不适用于真实的 videoView 显示
【发布时间】:2026-02-23 09:20:02
【问题描述】:

我有一个带有远程视频源的 AVPlayer。使用observeValueForKeyPath:ofObject:change:context:检测readyToPlay状态为on,并将AVPlayerLayer设置为myVideoContainerView的图层进行显示。

问题是:readyToPlay 状态被触发后。视频在屏幕上真实显示时会延迟 1-2 秒。

我尝试在readyToPlay 状态开启之前和之后设置 AVPlayerLayer。但它们都不起作用。

仅当我使用AVPlayer+AVPlayerLayer 时才会出现此问题。使用AVPlayerViewController 很好。但我仍然需要在我的项目中解决这个问题。

感谢您的任何建议!

     @property (weak, nonatomic) IBOutlet UIView *myVideoContainter;
     @property AVPlayer *player;
     @property AVPlayerLayer *layer;

-(void)viewDidLoad{
     self.player = [AVPlayer playerWithUR:videoURL];
     [self.player addObserver:self forKeyPath:@"status" options:0 context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                    change:(NSDictionary *)change context:(void *)context {
if (object == self.player && [keyPath isEqualToString:@"status"]) {
    if (self.player.status == AVPlayerStatusReadyToPlay) {
        NSLog(@"Ready To Play");
        self.layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        self.layer.frame = self.mainContentView.bounds;
        [self.mainContentView.layer addSublayer:self.layer];
        }
    }
}

【问题讨论】:

    标签: ios avplayer avplayerlayer


    【解决方案1】:

    问题已解决。

    不知道为什么,但player.currentItem.statusplayer.status 更准确。

    [self.player.currentItem addObserver:self forKeyPath:@"status" options:0 context:nil];
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                    change:(NSDictionary *)change context:(void *)context {
        if(self.player.currentItem.status == AVPlayerItemStatusReadyToPlay){
            //do something        
        }
    }
    

    注意。一些操作会改变AVPlayerItem.status。应该以这种方式处理循环问题。

    【讨论】:

      最近更新 更多