swiftavfoundationavplayercmtimensvalue

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


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?


Solution

  • 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