gpt4 book ai didi

swift - Avplayer总是从头开始

转载 作者:行者123 更新时间:2023-11-30 12:46:38 24 4
gpt4 key购买 nike

我试图让 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

最佳答案

我找到了解决方案,

  1. 我使用此代码从 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()

}

这是一个解决方案,但不是一个完美的解决方案,每次它重新下载音频文件以恢复它,这意味着如果我播放一个文件然后我返回到桌面 View 然后返回,它会钱包并等待几秒钟然后播放从它停止的地方开始。

关于swift - Avplayer总是从头开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41557013/

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