目前我正在使用swift 3.0中的一个项目,我有一个UISlider跟踪歌曲的progressTime并相应地更新值。因此,当progressTime继续时,它会更新其值并且滑块开始移动,因此一旦progressTime结束,滑块就会停止。在达到此目的的同时,我的要求是如果用户将滑块拖动到特定的随机位置,则从该点播放歌曲。因此,无论用户拖动滑块,歌曲都应播放该特定时间的歌曲。我的部分完成的代码如下,我将如何更改函数中的逻辑?
func trackTime() {
let interval = CMTime(value: 1, timescale: 2)
player?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { (progressTime) in
let seconds = CMTimeGetSeconds(progressTime)
let secondsString = String(format:"%02d", Int(seconds.truncatingRemainder(dividingBy: 60)))
let minutesString = String(format:"%02d", Int(seconds/60))
//progress bar and end time
if let duration = self.player?.currentItem?.asset.duration {
let durationSeconds = CMTimeGetSeconds(duration)
let endTimeSeconds = String(format:"%02d", Int(durationSeconds/60))
self.progressSlider.value = Float(seconds/durationSeconds)
self.progressSlider.isContinuous = false
let newDuration = durationSeconds - seconds
let endSecondsString = String(format:"%02d", Int(newDuration.truncatingRemainder(dividingBy: 60)))
self.endtime = "\(endTimeSeconds):\(endSecondsString)"
}
self.endTimeLabel.text = self.endtime
self.startTimeLabel.text = "\(minutesString):\(secondsString)"
})
}
一旦我按下播放按钮,它就像下面那样工作
@IBAction func playButtonPressed(_ sender: Any) {
if newRowSelected == true{
if(isNewPathSelected){
print("player")
let url:URL = savePath!
playerItem = AVPlayerItem(url: url as URL)
player=AVPlayer(playerItem: playerItem!)
let playerLayer=AVPlayerLayer(player: player!)
playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 50) // actually this player layer is not visible
self.view.layer.addSublayer(playerLayer)
isNewPathSelected = false
}
if player?.rate == 0 // this means if its not playing
{
print("Playing")
player!.play()
playButton.setImage(UIImage(named: "pause_button"), for: UIControlState.normal)
trackTime()
} else {
player!.pause()
playButton.setImage(UIImage(named: "play_button"), for: UIControlState.normal)
}
}else{
showAlert()
}
}
答案 0 :(得分:0)
试试这个
添加滑块选择器方法如下:
self.progressSlider.addTarget(self, action: Selector("touchUp:"), forControlEvents: [UIControlEvents.TouchUpInside])
滑块的选择器方法
func touchUp(sender:AnyObject?) {
var showingTime: : CMTime = CMTimeMakeWithSeconds(slider.value, 1);
player.seek(toTime: showingTime, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
}
答案 1 :(得分:0)
@IBAction func sliderValueChanged(_ sender: UISlider) {
// var showingTime: CMTime = CMTimeMakeWithSeconds(Float64(sender.value), 1);
if let duration = player?.currentItem?.duration {
let totalsecs = CMTimeGetSeconds(duration)
let val = Float64(sender.value) * totalsecs
let seekTime = CMTime(value: Int64(val), timescale: 1)
player?.seek(to: seekTime, completionHandler: { (completedSeek) in
})
}
}