获取视频的总时长
typedef struct
{
CMTimeValue value; /*! @field value The value of the CMTime. value/timescale = seconds. */
CMTimeScale timescale; /*! @field timescale The timescale of the CMTime. value/timescale = seconds. */
CMTimeFlags flags; /*! @field flags The flags, eg. kCMTimeFlags_Valid, kCMTimeFlags_PositiveInfinity, etc. */
CMTimeEpoch epoch; /*! @field epoch Differentiates between equal timestamps that are actually different because
of looping, multi-item sequencing, etc.
Will be used during comparison: greater epochs happen after lesser ones.
Additions/subtraction is only possible within a single epoch,
however, since epoch length may be unknown/variable. */
} CMTime;
- 1.官方给出公式 :value / timescale = seconds 其中value是视频的总帧数 timescale:视频帧率(帧/s)
AVPlayerItem的Duration属性就是一个CMTime类型的数据。所以获取视频的总时长(秒)需要duration.value/duration.timeScale - 系统也给出一个方法 直接获取视频CMTimeGetSeconds(CMTime time) ,当然这个方法最终也是根据参数time.value / time.timescale 来计算时长,此时参数是整个视频的返回的就是整个视频的时长,如果参数time只是一部分视频那么返回就是这部分视频时长。
/*!
@function CMTimeGetSeconds
@abstract Converts a CMTime to seconds.
@discussion If the CMTime is invalid or indefinite, NAN is returned. If the CMTime is infinite, +/- __inf()
is returned. If the CMTime is numeric, epoch is ignored, and time.value / time.timescale is
returned. The division is done in Float64, so the fraction is not lost in the returned result.
@result The resulting Float64 number of seconds.
*/
CM_EXPORT
Float64 CMTimeGetSeconds(
CMTime time)
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0);
刷新播放进度和状态
实时更新当前播放时间状态,AVPlayer已经提供了方法:
addPeriodicTimeObserverForInterval: queue: usingBlock。当播放进度改变的时候方法中的回调会被执行。我们可以在这里做刷新时间的操作
__weak __typeof(self) weakSelf = self;
[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//当前播放的时间
NSTimeInterval currentTime = CMTimeGetSeconds(time);
//视频的总时间
NSTimeInterval totalTime = CMTimeGetSeconds(weakSelf.player.currentItem.duration);
//设置滑块的当前进度
weakSelf.sliderView.value = currentTime/totalTime;
//设置显示的时间:以00:00:00的格式
weakSelf.currentPlayTimeLabel.text = [weakSelf formatTimeWithTimeInterVal:currentTime];
}];
快进或者快退到指定时间点播放
AVPlayer实例调用
- (void)seekToTime:(CMTime)time completionHandler:(void (^)(BOOL finished))completionHandler NS_AVAILABLE(10_7, 5_0);
//UISlider的响应方法:拖动滑块,改变播放进度
- (IBAction)sliderViewChange:(id)sender {
if(self.player.status == AVPlayerStatusReadyToPlay){
NSTimeInterval playTime = self.sliderView.value * CMTimeGetSeconds(self.player.currentItem.duration);
CMTime seekTime = CMTimeMake(playTime, 1);
[self.player seekToTime:seekTime completionHandler:^(BOOL finished) {
}];
}
}