Reputation: 1513
I am trying to make video player where I need to show the progress via UISlider and UILabel(for updating time). Here is my code
let videoPlayer = AVPlayer()
var videoPlayerSlider: UISlider = UISlider()
var videoPlayerLabel: UILabel = UILabel()
func updateVideoPlayerSlider() {
guard let currentTime = videoPlayer.currentTime else {
return
}
let mins = currentTime / 60
let secs = currentTime.truncatingRemainder(dividingBy: 60)
let timeformatter = NumberFormatter()
timeformatter.minimumIntegerDigits = 2
timeformatter.minimumFractionDigits = 0
timeformatter.roundingMode = .down
guard let minsStr = timeformatter.string(from: NSNumber(value: mins)), let secsStr = timeformatter.string(from: NSNumber(value: secs)) else {
return
}
videoPlayerLabel.text = "\(minsStr).\(secsStr)"
videoPlayerSlider.value = Float(videoPlayer.currentTime())
}
It shows 2 error.
1.(at very 1st line of the function)Initializer for conditional binding must have optional type, not '() -> CMTime
2.(at last line of the function)Cannot invoke initializer for type 'Float' with an argument list of type '(CMTime)'
Any assistance would be appreciated.
Upvotes: 2
Views: 7916
Reputation: 1224
let videoPlayer = AVPlayer()
var videoPlayerSlider: UISlider = UISlider()
var videoPlayerLabel: UILabel = UILabel()
func updateVideoPlayerSlider() {
// 1 . Guard got compile error because `videoPlayer.currentTime()` not returning an optional. So no just remove that.
let currentTimeInSeconds = CMTimeGetSeconds(videoPlayer.currentTime())
// 2 Alternatively, you could able to get current time from `currentItem` - videoPlayer.currentItem.duration
let mins = currentTimeInSeconds / 60
let secs = currentTimeInSeconds.truncatingRemainder(dividingBy: 60)
let timeformatter = NumberFormatter()
timeformatter.minimumIntegerDigits = 2
timeformatter.minimumFractionDigits = 0
timeformatter.roundingMode = .down
guard let minsStr = timeformatter.string(from: NSNumber(value: mins)), let secsStr = timeformatter.string(from: NSNumber(value: secs)) else {
return
}
videoPlayerLabel.text = "\(minsStr).\(secsStr)"
videoPlayerSlider.value = Float(currentTimeInSeconds) // I don't think this is correct to show current progress, however, this update will fix the compile error
// 3 My suggestion is probably to show current progress properly
if let currentItem = videoPlayer.currentItem {
let duration = currentItem.duration
if (CMTIME_IS_INVALID(duration)) {
// Do sth
return;
}
let currentTime = currentItem.currentTime()
videoPlayerSlider.value = Float(CMTimeGetSeconds(currentTime) / CMTimeGetSeconds(duration))
}
}
I hope this would help you
Upvotes: 5