How do I convert a CMTime to an NSValue in Swift?
Asked Answered
O

1

7

I was trying to make use of AVPlayer's addBoundaryTimeObserverForTimes method from swift and ran into a problem converting CMTimes to NSValues, which is what addBoundaryTimeObserverForTimes take as input. In the end I resorted to wrapping [NSString valueWithCMTime:] in a C function and calling it from swift, but is there a way to do it in pure swift?

Osmium answered 17/10, 2014 at 17:15 Comment(0)
T
12

The Swift constructor corresponding to valueWithCMTime: is NSValue(time:):

import CoreMedia
import AVFoundation

let cmTime  = CMTimeMake(value: 10, timescale: 20) // Updated for Swift 3+
let cmValue = NSValue(time: cmTime)
// Or simply:
let cmValue = cmTime as NSValue
Temper answered 17/10, 2014 at 17:49 Comment(2)
The problem was I wasn't importing CoreMedia. For some reason I thought the CMTime constructor for NSValue was defined in AVFoundation. Thanks!Osmium
For swift 3 have a look here: https://mcmap.net/q/1483637/-nsvalue-cmtime-in-swift-3Madoc

© 2022 - 2024 — McMap. All rights reserved.