我正在音频播放器上工作,我必须允许音频在后台播放,我已经完成了音频会话,但是当我在后台播放音频时我停留在进度栏中,然后再次打开我的应用程序进度栏,计时器停止了,我还需要在后台运行它们。我的意思是,如果我移到其他视图或最小化该应用程序,则应该使用计时器更新进度栏。
@IBAction func btnPlayMusicAction(_ sender: Any)
{
if isPlaying == false {
self.btnPlayMusicPro.setImage(#imageLiteral(resourceName: "PauseIcon"), for: .normal)
self.isPlaying = true
self.audioPlayer?.play()
timer = Timer.scheduledTimer(timeInterval:1.0, target: self,selector: (#selector(updateRemainingTime)), userInfo: nil, repeats:true)
}else{
self.btnPlayMusicPro.setImage(#imageLiteral(resourceName: "PlayIcon"), for: .normal)
self.isPlaying = false
if (audioPlayer?.isPlaying)!{
self.audioPlayer?.pause()
}
self.timer?.invalidate()
}
}
她是方法updateRemainingTime()
@objc func updateRemainingTime(){
let currentTime = Int((audioPlayer?.currentTime)!)
let duration = Int((audioPlayer?.duration)!)
let seconds = currentTime % 60
let minutes = (currentTime / 60) % 60
let hours = (currentTime / 3600)
var remainingTime:String = ""
if currentTime >= 3600{
remainingTime = String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}else{
remainingTime = String(format: "%02d:%02d", minutes, seconds)
}
self.lblPlayMusicTimePro.text = remainingTime
Tray.remainingAudioTime = remainingTime
if currentTime == duration-1{
timer?.invalidate()
if (audioPlayer?.isPlaying)!{
self.audioPlayer?.currentTime = 0
self.audioPlayer?.stop()
}
self.btnPlayMusicPro.setImage(#imageLiteral(resourceName: "PlayIcon"), for: .normal)
self.isPlaying = false
self.musicProgressViewPro.setProgress(0.0, animated: true)
self.lblPlayMusicTimePro.text = "00:00"
self.lblMusicTimePro.text = "00:00"
}else {
let currentProgress = Float((audioPlayer?.currentTime)! / (audioPlayer?.duration)!)
Tray.progressTime = currentProgress
self.musicProgressViewPro.setProgress(currentProgress, animated: true)
}
}