iosswiftcmtime

Converting CMTime values to swift


I have the following 2 lines of code that I am moving to Swift but I am a little stuck.

CMTime trimmingTime = CMTimeMake(lround(videoAsset.naturalTimeScale / videoAsset.nominalFrameRate), videoAsset.naturalTimeScale);
CMTimeRange timeRange = CMTimeRangeMake(trimmingTime, CMTimeSubtract(videoAsset.timeRange.duration, trimmingTime));

When converting the below line to begin with I get the following error.

var trimmingTime: CMTime
trimmingTime = CMTimeMake(value: lround(videoAsset.naturalTimeScale / videoAsset.nominalFrameRate), timescale: videoAsset.naturalTimeScale)

Binary operator '/' cannot be applied to operands of type 'CMTimeScale' (aka 'Int32') and 'Float'

I have tried a few different approaches but nothing seems to work.


Solution

  • You can not simply perform mathematically operation with different type of operands in swift like other languages. You need to type-cast manually.

    Here you should cast videoAsset.naturalTimeScale( which is CMTimeScale and CMTimeScale is of type Int32) to Float to get it work.

    Float(videoAsset.naturalTimeScale)
    

    But CMTimeMake's value key will accept value CMTimeValue type value. So use it like:

    trimmingTime = CMTimeMake(value: CMTimeValue(Float(videoAsset.naturalTimeScale) / videoAsset.nominalFrameRate), timescale: videoAsset.naturalTimeScale)
    

    Again to make you code more Swifty use CMTime rather CMTimeMake as:

    trimmingTime = CMTime(value: CMTimeValue(Float(videoAsset.naturalTimeScale) / videoAsset.nominalFrameRate), timescale: videoAsset.naturalTimeScale)