I have two sounds (ping and alarm) that should be played when the respective conditions are fulfilled. Both sounds are played repeatedly. It is possible that both sounds overlap with each other, which is why I declared a separate AVAudioPlayer to play each sound (pingPlayer and alarmPlayer).
Type of freeze: Ping and alarm play properly on their own, but when both are activated, the whole app freezes at the beginning.
Type of freeze: When only the alarm is activated with additional pause or stop statements in the code, the app freezes as well.
import AVFoundation
private var pingPlayer: AVAudioPlayer?
private var alarmPlayer: AVAudioPlayer?
func playPing() {
guard let url = Bundle.main.url(forResource: "ping", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
pingPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = pingPlayer else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
alarmPlayer is initialised in viewDidLoad() Because when the alarmPlayer is initialised in a separate function (like playPing()), the app still freezes.
override viewDidLoad() {
//...
guard let url = Bundle.main.url(forResource: "alarm", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
alarmPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
} catch let error {
print(error.localizedDescription)
}
}
//alarmPlayer is then called after the condition like this:
alarmPlayer?.prepareToPlay()
alarmPlayer?.play()
- Type of freeze: called after a certain condition is fulfilled
alarmPlayer?.stop() //or alarmPlayer?.pause()