我有一个函数,它可以播放一首歌,我在它的参数中给出了URL。我正在使用AVPlayer来做这件事。
func playSong(url:URL) {
self.playerItem = AVPlayerItem(url: url)
self.avPlayer = AVPlayer(playerItem: playerItem)
self.avPlayer.automaticallyWaitsToMinimizeStalling = false
self.avPlayer!.volume = 1.0
self.avPlayer.play()
let duration = (self.avPlayer.currentItem?.asset.duration)!
let totalDuration : CMTime = duration
let seconds : Float64 = CMTimeGetSeconds(totalDuration)
self.totalAudioPlaybackTime.text = self.stringFromTimeInterval(interval: seconds)
self.sliderProgress.maximumValue = Float(seconds)
self.timeObserver = self.avPlayer.addPeriodicTimeObserver(forInterval: CMTime.init(value: 1, timescale: 1), queue: .main, using: { time in
if let duration = self.avPlayer.currentItem?.duration{
let time : Float64 = CMTimeGetSeconds(self.avPlayer!.currentTime())
self.sliderProgress.value = Float(time)
self.currentTime.text = self.stringFromTimeInterval(interval: time)
}
})
}
字符串
其他一切都很好,但唯一的问题是在线路
let duration = (self.avPlayer.currentItem?.asset.duration)!
型
当这一行被执行时,它需要5到6秒(有时甚至10秒)来计算持续时间,而当这发生时,UI只是冻结,直到计算出持续时间。我不知道为什么会这样。请让我知道我做错了什么
1条答案
按热度按时间piv4azn71#
您应该从后台线程加载
duration
。您可以使用新的Swift并发
字符串
苹果文档:https://developer.apple.com/documentation/avfoundation/media_assets/loading_media_data_asynchronously