使用avplayer.currentitem?.sast.Duration使UI停止一段时间
我的功能可以用我在参数中给出的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只是冻结了直到计算持续时间。我不知道为什么会发生这种情况。请让我知道我在做什么错
I have a function that plays a song with the url i have given in it's parameters. I am using AVPlayer to do this.
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)
}
})
}
Everything else is working fine but the only issue is at the line
let duration = (self.avPlayer.currentItem?.asset.duration)!
When ever this line is executed it takes 5 to 6 seconds(sometimes even 10) to calculate the duration and while that is happening the UI just freezes until the duration is calculated. I have no idea why that is happening. Kindly let me know what i am doing wrong
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该从背景线程加载
持续时间
。您可以使用新的Swift并发
苹果文档:
You should load
duration
from the background thread.You can use the new swift concurrency
Apple Docs:
https://developer.apple.com/documentation/avfoundation/media_assets/loading_media_data_asynchronously