2016-07-15 128 views

回答

6

据我所知,我同意你的看法,有从调用play()函数到视频实际播放(换句话说,视频的第一帧被渲染的时间)之间有轻微的延迟。延迟取决于一些标准,例如视频类型(视频点播或直播),网络状况......但幸运的是,无论何时呈现视频的第一帧,我的意思是视频实际播放的时间。

通过观察当前AVPlayerItemstatus,并且每当它是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") 
    } 
} 

顺便提一下,还有另一种解决方案,我们观察到的AVPlayerLayerreadyForDisplay状态,这也表明,每当视频呈现。然而,这种解决方案具有苹果文件

/*! 
    @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"); 
    } 
} 

Thereotically,[self.playerLayer isReadyForDisplay]然而,应该返回YES,作为文档,它不guaranted。

我希望这会有所帮助。

+0

我觉得它非常有帮助。我目前正在使用“self.player!.addBoundaryTimeObserverForTimes([NSValue(CMTime:CMTimeMake(1,20))],队列:nil,usingBlock:{()”并且它不是100%的时间发射,我是目前正在寻找你的解决方案,给我一个小时,我会更新如果它的工作,谢谢! –

+2

我不得不添加更多的东西,这是测试,如果状态是AVPlayerStatusReadyToPlay AND player.rate> 0.我需要确保播放器正在播放,但除此之外,完美答案 –

+0

@ JoshO'Connor很高兴听到这个消息,谢谢。 – HDT

5

对于视频

AVPlayer有一个名为rate (Float)的说法,如果rate大于0.0,那里正在播放的视频。

您可以检查是否rate!=0:(速度可以为负,如果玩家会倒流)

if vidPlayer != nil && vidPlayer.rate != 0 { 
    println("playing") 
} 

AVPlayer class reference

+0

AVPlayer可以播放视频。我不是在谈论AVAudioPlayer –

+0

是的。我在12小时前编辑了答案,并删除了这部分,至于@SohilR的建议。认为它可以对其他用户有所帮助。发布的代码是AVPlayer,而不是AVAudioPlayer。 – Idan

+0

编辑答案澄清。 – Idan