您如何检测何时播放AVPlayer?在调用play()函数与实际播放视频之间似乎存在一些延迟。

最佳答案

据我所知,我同意您的看法,即在调用play()函数与实际播放视频之间存在一点延迟(换句话说,就是渲染视频的第一帧的时间)。延迟取决于某些标准,例如视频类型(VOD或实时流式传输),网络状况等。但是,幸运的是,我们能够知道何时渲染视频的第一帧,我的意思是确切地说,何时播放视频。

通过观察当前statusAVPlayerItem,无论何时是AVPlayerItemStatusReadyToPlay,都应该渲染第一帧。

[self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:NULL];

-(void)observeValueForKeyPath:(NSString*)path ofObject:(id)object change:(NSDictionary*)change context:(void*) context {

    if([self.playerItem status] == AVPlayerStatusReadyToPlay){
        NSLog(@"The video actually plays")
    }
}

顺便说一句,还有另一种解决方案,我们观察readyForDisplayAVPlayerLayer状态,它还指示何时渲染视频。但是,此解决方案具有Apple文档中提到的缺点。
/*!
     @property      readyForDisplay
     @abstract      Boolean indicating that the first video frame has been made ready for display for the current item of the associated AVPlayer.
     @discusssion   Use this property as an indicator of when best to show or animate-in an AVPlayerLayer into view.
                    An AVPlayerLayer may be displayed, or made visible, while this propoerty is NO, however the layer will not have any
                    user-visible content until the value becomes YES.
                    This property remains NO for an AVPlayer currentItem whose AVAsset contains no enabled video tracks.
 */
@property(nonatomic, readonly, getter=isReadyForDisplay) BOOL readyForDisplay;

这是示例代码
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
[self.playerLayer addObserver:self forKeyPath:@"readyForDisplay" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:NULL];

-(void)observeValueForKeyPath:(NSString*)path ofObject:(id)object change:(NSDictionary*)change context:(void*) context {
    if([self.playerLayer isReadyForDisplay]){
        NSLog(@"Ready to display");
    }
}

因此,[self.playerLayer isReadyForDisplay]应该返回YES,但是,作为文档,它没有保证。

我希望这会有所帮助。

关于ios - 检测何时播放AVPlayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38387739/

10-12 13:37