簡體   English   中英

Swift - 通過UISlider進行AVPlayer

[英]Swift - AVPlayer progress via UISlider

我正在嘗試制作視頻播放器,我需要通過UISliderUILabel顯示進度(用於更新時間)。 這是我的代碼

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.(在函數的第1行)條件綁定的初始化程序必須具有可選類型,而不是'() - > CMTime

2.(在函數的最后一行)無法使用類型為“(CMTime)”的參數列表調用類型為“Float”的初始值設定項

任何援助將不勝感激。

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

我希望這會對你有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM