这些点我们有必要注意一下
1、CMTime 一个专门用于标识视频时间的结构体
/*!
@typedef CMTime
@abstract Rational time value represented as int64/int32.
*/
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;
前面的代码中我们看到有一个获取视频总长度的方法:
CMTime duration = avplayeritem.duration;
NSLog(@"视频总时长:%.2f",CMTimeGetSeconds(duration));
可以看到CMTimeGetSeconds这个函数把一个CMTime类型转化成一个浮点型,如果一个影片为60帧/每秒, 当前想要跳转到120帧的位置,也就是两秒的位置,那么就可以创建一个 CMTime 类型数据。它通常可以用下面两个函数来创建.
1>: CMTimeMake(int64_t value, int32_t scale) Eg: CMTime time1 = CMTimeMake(120, 60);
2>:CMTimeMakeWithSeconds(Flout64 seconds, int32_t scale) Eg: CMTime time2 = CMTimeWithSeconds(120, 60);
CMTimeMakeWithSeconds 和 CMTimeMake 区别在于,第一个函数的第一个参数可以是float,其他一样。
- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(nullable dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;
比如说:我们把时间间隔设置为, 1/ 10 秒,然后 block 里面更新 UI。就是一秒钟更新10次UI,我们验证一下:
[self.avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 10) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
// CMTime的timescale的定义帮助理解下面代码
// @field timescale The timescale of the CMTime. value/timescale = seconds.
float currentPlayTime = (double)self.avPlayerItem.currentTime.value/ self.avPlayerItem.currentTime.timescale;
NSLog(@"当前播放进度:%f",currentPlayTime);
}];
我们随便截取出一段打印的日志,看一下结果就可以验证:











