我使用AVPlayer播放音频文件。我有问题。 UISlider无法正常工作,滑块应作为进度视图移动,当您单击停止时,音频将再次播放
@IBAction func play(_ sender: Any) {
let url = URL(string: self.urlAudio[0])
let playerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem:playerItem)
player.rate = 1.0;
player.play()
let duration : CMTime = playerItem.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)
playbackSlider.maximumValue = Float(seconds)
playbackSlider.isContinuous = true
playbackSlider.tintColor = UIColor.green
playbackSlider.addTarget(self, action: #selector(ViewControllerAudioDetail.playbackSliderValueChanged(_:)), for: .valueChanged)
if soundChange == true{
playChange.setImage(UIImage(named:"Pause.png"), for: UIControlState.normal)
soundChange = false
player.play()
} else {
playChange.setImage(UIImage(named:"Play.png"), for: UIControlState.normal)
soundChange = true
player.pause()
}
}
func playbackSliderValueChanged(_ playbackSlider:UISlider){
let seconds : Int64 = Int64(playbackSlider.value)
let targetTime:CMTime = CMTimeMake(seconds, 1)
player.seek(to: targetTime)
}
答案 0 :(得分:0)
单击停止时,再次播放音频
为了切换播放和暂停检查是否正在播放avplayer。如果播放暂停,则播放它。
if player.rate == 0 {
player.play()
//change your button image
}
else {
player.pause()
//change your button image
}
滑块应作为进度视图移动
您可以使用AVPlayer的PeriodicTime Observer更新滑块进度
let _ = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in
self?.audioPlayerSlider.value = Float(CMTimeGetSeconds(time)) / Float(totalDuration)
}
<强> P.S:强>
每次用户点击按钮时都不要创建播放器实例。仅在玩家为零或您想要播放不同曲目时创建。
@IBAction func play(_ sender: Any) {
if player == nil {
let url = URL(string: self.urlAudio[0])
let playerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem:playerItem)
player.rate = 1.0;
}
if player.rate == 0 {
player.play()
//change your button image
}
else {
player.pause()
//change your button image
}
}
修改强>
我相信你正试图找到一种方法来擦洗/寻找AVPlayer正在播放的特定音频时间。
你可以使用AVPlayer的搜索方法来做到这一点。
@IBAction func audioSliderDragged(_ sender: AnyObject) {
let value = self.audioPlayerSlider.value
let durationToSeek = Float(totalDuration) * value
player.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),player.currentItem!.duration.timescale)) { [weak self](state) in
//do what is relevant to your app on seeing to particular offset
}
}