在应用程序进入后台后,AVAudioPlayer会被暂停,因此获取currentTime时可能会返回不正确的值。要解决这个问题,可以在应用程序进入后台之前保存当前的currentTime,并在应用程序返回前台时恢复它。
以下是一个示例代码:
import AVFoundation
import UIKit
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
var currentTime: TimeInterval = 0.0 // 保存当前的currentTime
override func viewDidLoad() {
super.viewDidLoad()
// 初始化AVAudioPlayer
guard let filePath = Bundle.main.path(forResource: "audio", ofType: "mp3") else {
return
}
let url = URL(fileURLWithPath: filePath)
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.prepareToPlay()
} catch {
print("Failed to initialize AVAudioPlayer: \(error)")
}
// 注册应用程序进入后台和返回前台的通知
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc func applicationDidEnterBackground() {
// 保存当前的currentTime
currentTime = audioPlayer?.currentTime ?? 0.0
audioPlayer?.pause()
}
@objc func applicationWillEnterForeground() {
// 恢复之前保存的currentTime并继续播放音频
audioPlayer?.currentTime = currentTime
audioPlayer?.play()
}
}
在这个示例中,我们使用AVAudioPlayer来播放一个名为"audio.mp3"的音频文件。当应用程序进入后台时,我们保存当前的currentTime,并在应用程序返回前台时恢复它并继续播放音频。