iosswiftswift3cmtime

Cant convert Swift CMTimeRange to Float or get the number?


Im having a data type issue - with AVPlayer in Swift I am given a CMTimeRange when I try to get:

AudioPlayerManager.shared.currentTrack?.playerItem?.loadedTimeRanges[0]

What is printed with this is:

Optional(CMTimeRange: {{0/1 = 0.000}, {1016722/600 = 1694.537, rounded}})

I have tried all the members and trying to get a value for the cmtimerange key here, but I just get errors. I need the final value the 1694 as a Float.

How do I do this?


Solution

  • A CMTimeRange is just that, a range of times. It has start, end, and duration properties. Each of those is a CMTime. CMTime has a seconds property as a Double.

    if let range = AudioPlayerManager.shared.currentTrack?.playerItem?.loadedTimeRanges[0] {
        let seconds = Float(range.duration.seconds)
    }
    

    This will give you the number of seconds as a Float. Change duration to end if that's what you need.