gpt4 book ai didi

swift - 如何在不获取 nan 的情况下获取 CurrentItem.duration

转载 作者:行者123 更新时间:2023-11-28 05:38:41 34 4
gpt4 key购买 nike

我正在关注 A simple iOS view to play video这可以帮助您在 UIView 中显示 AVPlayer。这非常有帮助,但不幸的是在 VideoView(自定义创建)中它不包含 currentItem?.duration所以,我尝试通过这种方式自己添加它:

   func getCurrentItemDuration() -> Double
{
let duration = player?.currentItem?.duration
let durationSeconds = CMTimeGetSeconds(duration!)
return durationSeconds
}

但是当我尝试在我的 UIViewController 中打印它时,我得到:Nan

class VideoView: UIView {

var playerLayer: AVPlayerLayer?
var player: AVPlayer?
var isLoop: Bool = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

func configure(url: String) {
if let videoURL = URL(string: url) {


player = AVPlayer(url: videoURL)
playerLayer = AVPlayerLayer(player: player)
playerLayer?.frame = bounds
playerLayer?.videoGravity = AVLayerVideoGravity.resize

if let playerLayer = self.playerLayer {
layer.addSublayer(playerLayer)
}
NotificationCenter.default.addObserver(self, selector: #selector(reachTheEndOfTheVideo(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
}
}

func play() {
if player?.timeControlStatus != AVPlayer.TimeControlStatus.playing {
player?.play()
}
}

func pause() {
player?.pause()
}

func stop() {
player?.pause()
player?.seek(to: CMTime.zero)
}

func getCurrentItemDuration() -> Double
{
let duration = player?.currentItem?.duration
let durationSeconds = CMTimeGetSeconds(duration!)
return durationSeconds
}
@objc func reachTheEndOfTheVideo(_ notification: Notification) {
if isLoop {
player?.pause()
player?.seek(to: CMTime.zero)
player?.play()
}
}
}

我不知道如何修复这个错误,所以如果有人熟悉这个错误,请指导我修复它。 :)

感谢您的宝贵时间。

最佳答案

因为您想获得 Assets 的持续时间。所以,尝试使用:

CMTimeGetSeconds(player.currentItem!.asset.duration)

它将以秒为单位为您提供当前播放项目的持续时间。

关于swift - 如何在不获取 nan 的情况下获取 CurrentItem.duration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57715324/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com