我正试图让Avplayer从停止的位置恢复,通过创建CMtime类型的全局值并存储当前时间,然后使用它从停止的地方恢复
我的代码:
override func viewDidLoad() {
super.viewDidLoad()
url = URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")!
let playerItem:AVPlayerItem = AVPlayerItem(url: url as URL)
player = AVPlayer(playerItem: playerItem)
let duration : CMTime = playerItem.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)
playbackSlider!.maximumValue = Float(seconds)
playbackSlider?.addTarget(self, action: #selector(playbackSliderValueChanged(_:)), for: .valueChanged)
self.view.addSubview(playbackSlider!)
player!.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: DispatchQueue.main) { (CMTime) -> Void in
if player!.currentItem?.status == .readyToPlay {
let time : Float64 = CMTimeGetSeconds(player!.currentTime())
self.playbackSlider!.value = Float (time) }}
@IBAction func playbackSliderValueChanged(_ sender: UISlider) {
let seconds : Int64 = Int64(playbackSlider.value )
let targetTime:CMTime = CMTimeMake(seconds, 1)
player!.seek(to: targetTime)
if player!.rate == 0
{
player?.play()
}
}
当我尝试使用seek(to :) 没有改变它也从一开始就开始了!
我尝试使用
更改当前时间 if let currentTime = player?.currentTime() {
player?.seek(to: times2! )
}
我不知道为什么它总是从头开始 我使用的是AVAudioPlayer,它比AVplayer容易得多 但因为我需要传输音频,我将其更改为AVplayer
答案 0 :(得分:0)
我找到了解决方案,
我使用此代码从CMtime获得秒数,并将其添加到Unwind segue函数
let t1 = Float((player?.currentTime().value)!)
let t2 = Float((player?.currentTime().timescale)!)
times2 = t1 / t2
// time2 is a global value of type float
nameOfTheAudioWasPlaying = Array[SelectedRow].Title! // nameOfTheAudioWasPlaying is also a global value of type String
2.在viewdidload中我使用此代码
if Array[SelectedRow].Title! == nameOfTheAudioWasPlaying {
player?.seek(to: CMTimeMakeWithSeconds(Float64(times2), 1) )
player?.play()
}else {
player?.play()
}
这是一个解决方案,但不是一个完美的解决方案,每次重新下载一个音频文件来恢复它,这意味着如果我播放一个文件,然后我返回tableview然后返回,它会钱包并等待一秒然后播放从它停止的地方开始。