2017-02-19 88 views
1

我試圖讓視頻播放器,我需要通過UISlider的UILabel顯示進度(更新時間)AVPlayer進展。這是我的代碼斯威夫特 - 通過UISlider

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()) 
    } 

它顯示2錯誤。

1(在功能非常一號線)初始值設定條件的結合必須有可選的類型,而不是「() - > CMTime

2.(在函數的最後一行)無法調用類型初始化'漂浮'與參數列表類型'(CMTime)'

任何援助,將不勝感激。

+0

...第一誤差在函數的1號線發生(後衛讓語句)和第2個錯誤的發生最後一行 –

+0

我解釋 –

回答

2
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)) 
    } 
} 

我希望這會幫助你

其中直插U面對這個錯誤