The issue was that my app was being suspended by iOS in the background before it could prepare and play the sound. To fix this, I used a background task to request execution time from the system while preparing and playing the audio.
var bgTask: UIBackgroundTaskIdentifier = .invalid
func beginBackgroundTask() {
bgTask = UIApplication.shared.beginBackgroundTask {
UIApplication.shared.endBackgroundTask(self.bgTask)
self.bgTask = .invalid
}
}
Call beginBackgroundTask
right before your code to play the audio.
beginBackgroundTask()
guard let url = Bundle.main.url(forResource: "TimerDone", withExtension: "wav") else { return }
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.play()
} catch {
print("Audio playback error: \(error.localizedDescription)")
}