Xcode 6- SWIFT- Cast CMTime as Float
Asked Answered
K

2

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

tableView.reloadData()

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

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

player.replaceCurrentItemWithPlayerItem(currentItem)

player.play()

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.

Kristlekristo answered 17/9, 2014 at 15:22 Comment(0)
S
34

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)
Sartorius answered 17/9, 2014 at 15:36 Comment(2)
Yeah, that works Thank You @Martin PS: Is there a tip for figuring stuff like these on my own in the future? ( other than asking here of course :) ) i tried reading the CMTime reference but couldn't figure it out.Kristlekristo
@Abdou023: Well, CMTimeGetSeconds() is documented in developer.apple.com/library/prerelease/ios/documentation/…. You can also cmd-click on a type or method in the Swift source file (e.g. on CMTime), that leads you to the Swift definition where you then find related methods.Sartorius
O
2

CMTime is a structure, containing a value, timescale, flags and epoch. So you cannot just "cast" it to a floating point value.

You can use the value by directly writing

sliderOutlet.value = Float(player.currentTime().value)

But this will only give the value of the player which is in milliseconds. To get the value in seconds you use this:

sliderOutlet.value = Float(CMTimeGetSeconds(player.currentTime()))

Mind well this might also won't be the correct way you should have the value of your slider.

Occident answered 6/12, 2017 at 13:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.