我正在为该项目使用AVFoundation,下面是我的代码。每当按下暂停按钮并再次按下播放按钮时,就会从头开始播放录制的音频,而不是从上次播放的位置开始播放。除了暂停部分之外,整个代码都能正常工作,并且经过了很多优化,结果如下:
private var audioPlayer: AVAudioPlayer?
private var audioRecorder: AVAudioRecorder?
@objc func playButtonPressed(sender: UIButton) { //The buttons are made programmatically therefore I'm using addTarget later on.
if let recorder = audioRecorder {
if !recorder.isRecording {
audioPlayer = try? AVAudioPlayer(contentsOf: recorder.url) //It plays the file saved in the expected url.
audioPlayer?.delegate = self
if let player = audioPlayer {
if !player.isPlaying {
playButton.setImage(#imageLiteral(resourceName: "play"), for: .normal)
stopButton.setImage(#imageLiteral(resourceName: "stop2"), for: .normal)
recordButton.setImage(#imageLiteral(resourceName: "record"), for: .normal)
player.play()
startTimer()
}
}
}
}
}
@objc func pauseButtonPressed(sender: UIButton) { //The buttons are hidden and shown through different user usage so I don't need a lot of code in here.
playButton.isHidden = false
pauseButton.isHidden = true
if let player = audioPlayer {
if player.isPlaying {
audioPlayer?.pause() //This is the only issue in code, it literally stops the playing audio, not pausing it.
pauseTimer()
}
}
}
我想也需要看看播放和暂停计时器功能。所有委托和必需的协议已添加到该类中。欢迎进行任何必要的更改。
private var timer: Timer?
func startTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in
self.elapSetTimeInSecond += 1
self.updateTimeLabel()
})
}
func pauseTimer() {
timer?.invalidate()
}