NSTimeInterval和CMTime

NSTimeInterval

众所周知,NSTimeInterval是一个把double进行typedef 重定义的一个类型,本质上还是一个表示64位浮点型数据类型double

CMTime

第一次接触应该是在项目中开发视频播放模块的时候接触到的,视频播放的时候需要展示视频播放进度的当前时间和视频总时长,发现获取这两个数据的方式是通过AVPlayerItem的duration属性和currentTime对象方法,而获取到的数据竟然是CMTime类型,一时间想到的就是我怎么把一个CMTime类型的数据转换成UIlabel上可以展示的NSString类型的字符串,所以,百度走起~
1、CMTime的定义:Defines a structure that represents a rational time value int64/int32。 苹果说是定义了一个分子是64位整数,分母是32位整数的有理数时间值。因为CMTime比NSTimeInterval更精确,所以音视频处理中时间就用CMTime

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是C语言的结构体,value表示分子,timescale表示分母,flag是一个枚举类型,表示时间的状态
2、初始化一个CMTime对象

 CMTimeMake(int64_t value, int32_t timescale)
 CMTimeMakeWithEpoch(int64_t value, int32_t timescale, int64_t epoch)
 CMTimeMakeWithSeconds(Float64 seconds, int32_t preferredTimescale) //可以把double的秒转换成CMTime对象

真实开发中,我们不禁会问我有当前播放的时间seconds,我可以通过CMTimeMakeWithSeconds得到一个AVPlayerItem可以接收到CMTime对象,可以preferredTimescale是个什么鬼?而我们看到CMTimeMake的参数也有个timescale
音视频中的时间都是按帧计算的,所以CMTimeMake(int64_t value, int32_t timescale)中,value就是当前播放到第几帧,timescale表示每秒的帧数, 而CMTimeMakeWithSeconds(Float64 seconds, int32_t preferredTimescale) 中,preferredTimescale建议我们使用“每秒的帧数”,那究竟是多少呢?

#define NSEC_PER_SEC 1000000000ull   //每秒有多少纳秒
#define NSEC_PER_MSEC 1000000ull    
#define USEC_PER_SEC 1000000ull   //每毫秒有多少毫秒
#define NSEC_PER_USEC 1000ull   //每毫秒有多少纳秒

3、CMTime类型时间的计算

 CMTimeAdd(CMTime addend1, CMTime addend2)
 CMTimeSubtract(CMTime minuend, CMTime subtrahend)
 CMTimeMultiply(CMTime time, int32_t multiplier)
 CMTimeMultiplyByRatio(CMTime time, int32_t multiplier, int32_t divisor)

4、最关心的把CMTime对象转换成我们熟悉的double类型

 CMTimeGetSeconds(CMTime time)

你可能感兴趣的:(NSTimeInterval和CMTime)