答案 0 :(得分:0)
代码中的问题是,您总是在play方法中创建一个新的播放器对象。这就是它始终从音频开头开始的原因。
class ViewControllerAudioDetail: UIViewController {
@IBOutlet var list: TableViewControllerAudioList!
@IBOutlet weak var playChange: UIButton!
@IBOutlet weak var timeAudio: UILabel!
@IBOutlet weak var playbackSlider: UISlider!
var player:AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "БИБЛИОТЕКА"
setupAudioPlayer()
}
func setupAudioPlayer(){
let url = URL(string: ViewControllerAudioDetail.urlAudio[0])
let playerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem:playerItem)
playbackSlider.tintColor = UIColor.green
let _ = player!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in
self?.updateSlider(time: time)
}
}
func updateSlider(time:CMTime){
let duration = CMTimeGetSeconds(player!.currentItem!.asset.duration)
self.playbackSlider.value = Float(CMTimeGetSeconds(time)) / Float(duration)
}
@IBAction func play(_ sender: Any) {
if player?.rate == 0 {
player?.rate = 1.0;
player?.play()
playChange.setImage(UIImage(named:"Pause.png"), for: UIControlState.normal)
} else {
playChange.setImage(UIImage(named:"Play.png"), for: UIControlState.normal)
player?.pause()
}
}
@IBAction func audioPlaybackSlider(_ sender: Any) {
//перемотка аудиозвука
let duration = CMTimeGetSeconds(player!.currentItem!.asset.duration)
let value = self.playbackSlider.value
let durationToSeek = Float(duration) * value
self.player?.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),player!.currentItem!.duration.timescale)) { [](state) in
}
}
}