19

I'm creating an app for playing a ringtone and I'd want to know the current time in milliseconds of the played ringtone every time.

CMTime cTime = player_.currentTime; float currentTime = cTime.value / cTime.timescale;

That currentTime here gets the value in seconds. How can I get the exact currentTime value but in milliseconds?

Cœur
  • 37,241
  • 25
  • 195
  • 267
nano
  • 2,511
  • 4
  • 25
  • 42

3 Answers3

59

There is a way to get current times in seconds, you can take 1000 times that and ther you have your miliseconds:

Float64 dur = CMTimeGetSeconds([player currentTime]);
Float64 durInMiliSec = 1000*dur;

Sadly you will have to use it as a float or Float64 you can't use that result as a CMTime

Praveenkumar
  • 24,084
  • 23
  • 95
  • 173
Samssonart
  • 3,443
  • 3
  • 31
  • 41
  • But how can we pass this Float value in the following function? - (BOOL)insertTimeRange:(CMTimeRange)timeRange ofTrack:(AVAssetTrack *)track atTime:(CMTime)startTime error:(NSError **)error; Because it takes CMTime as a parameter. – Developer Dec 27 '12 at 12:15
  • You can use the original time (in seconds) and create a CMTime with that value using the CMTimeMake function. – Samssonart Jan 15 '13 at 17:26
  • This decade-old answer still holds test of time. Much appreciated. Helped us solve an issue losing fraction of second in this [PR](https://github.com/luanpotter/audioplayers/pull/421). – om-ha Feb 17 '20 at 22:36
6

I think that the accepted answer loses detail. A more accurate way to get milliseconds would be the following:

let seconds : Double = Float64(time.value * 1000) / Float64(time.timescale)

If you convert to seconds first you'd lose precision.

Siyual
  • 16,415
  • 8
  • 44
  • 58
Trevis Thomas
  • 353
  • 3
  • 6
  • 1
    This is incorrect. From Apple's documentation on CMTimeGetSeconds "The division is done in Float64, so the fraction is not lost in the returned result." – amergin Aug 28 '17 at 17:04
2

CMTime.value and CMTime.timescale are both integers, so judging by your code, the result gets rounded and you don't get a precise timestamp. Try CMTimeGetSeconds instead.

Alex Chugunov
  • 728
  • 5
  • 10