Abdou23 Abdou23 - 1 year ago 493
Swift Question

Xcode 6- SWIFT- Cast CMTime as Float

var songs = MPMediaQuery()
var localSongs = songs.items
songList = NSMutableArray(array: localSongs)


var song = MPMediaItem(coder: songList[0] as NSCoder)

var currentItem = AVPlayerItem(URL: song.valueForProperty(MPMediaItemPropertyAssetURL) as NSURL)



var songTitle: AnyObject! = song.valueForProperty(MPMediaItemPropertyTitle)

songName.text = songTitle as? String

sliderOutlet.value = Float(player.currentTime()) // <<-Error here

I'm building a music player and I want a slider to show the duration of the song, but I get this error

Could not find an overload for 'init' that accepts the supplied arguments

I think the problem is converting CMTime to Float.

Answer Source

CMTime is a structure, containing a value, timescale and other fields, so you cannot just "cast" it to a floating point value.

Fortunately, there is a conversion function CMTimeGetSeconds():

let cmTime = player.currentTime()
let floatTime = Float(CMTimeGetSeconds(player.currentTime()))

Update: As of Swift 3, player.currentTime returns a TimeInterval which is a type alias for Double. Therefore the conversion to Float simplifies to

let floatTime = Float(player.currentTime)