我对Swift有点陌生。我的歌曲位置滑块效果很好。很顺利我发现的唯一问题是,如果将滑块放在同一位置的时间过长(超过一秒钟),它将产生奇怪的结果。如果这样做,您将获得很多。处理滑块的方法可能比我在这里做的要简单得多,但这已经很接近了。感谢您的帮助!
var myMPMusicPlayerController = MPMusicPlayerController.systemMusicPlayer
var notificationCenter = NotificationCenter.default
var sliderInUse: Bool! = false
var positionSliderTimer: Timer!
var songTimer: Timer!
var songDuration: Double!
var positionInSong: Double!
override func viewDidLoad() {
positionSliderTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(PlayerViewController.updatePositionOfSlider), userInfo: nil, repeats: true)
}
// ********** updateSongTimeDisplays() **********
@objc func updateSongTimeDisplays(_ songTime: Double) {
var currentTime: Int
if (self.myMPMusicPlayerController.nowPlayingItem != nil)
{
if self.sliderInUse == true {
currentTime = Int(songTime)
} else {
currentTime = Int(self.myMPMusicPlayerController.currentPlaybackTime)
}
let currentMinutes = currentTime/60
let currentSeconds = currentTime - currentMinutes * 60
songElapsedTime.text = NSString(format: "%02d:%02d", currentMinutes,currentSeconds) as String
let remainingTime = Int(songDuration) - currentTime
let remaningMinutes = remainingTime/60
let remainingSeconds = remainingTime - remaningMinutes * 60
songRemainingTime.text = NSString(format: "%02d:%02d", remaningMinutes,remainingSeconds) as String
} else {
// Reset the time to zero.
songElapsedTime.text = NSString(format: "%02d:%02d", 0,0) as String
}
}
// ********** positionSliderTapped() **********
@IBAction func positionSliderTapped(_ sender: Any) {
self.sliderInUse = true
positionInSong = TimeInterval(positionSlider.value)
updateSongTimeDisplays(positionInSong)
}
// ********** updatePositionOfSlider() **********
@objc func updatePositionOfSlider() {
if sliderInUse == false {
positionSlider.value = Float(self.myMPMusicPlayerController.currentPlaybackTime)
}
}
// ********** positionSliderReleased() **********
@objc func positionSliderReleased() {
self.sliderInUse = false
self.myMPMusicPlayerController.currentPlaybackTime = positionInSong
}
下面的大数字发生在滑动后将手指保持在一个位置
13 13 13 13 13 13 13 15 16 18岁 19 20 22 24 26 27 29 30 31 32 32 32 33 33 33 33 33 33 33 33 33 33 95654513522583 33 33 33 33 33 33 33 33 33 33 33 33 95656282321708 33 33 33 33 33 33 33
答案 0 :(得分:0)
经过进一步的测试和跟踪,我弄清楚了。当我的代码显式调用updateSongTimeDisplays(_ songTime:Double)时,没有问题,因为我传入了positionInSong。但是,当iOS调用间隔时执行的updateSongTimeDisplays(_ songTime:Double)时,iOS不会传入该参数。解决的办法是不传递参数。由于positionInSong被声明为该类的一部分,所以我不需要传递它。现在,它可以完美运行!