0

I have an app being used by people to receive orders with it needing to make a continuous sound until staff attend to it. It was working for two months then just started crashing a lot. For whatever reason, it runs fine on an iPad but not on iPhones running a recent operating system.

When this bit of code gets called it crashes:

guard let path = Bundle.main.path(forResource: "alert.mp3", ofType: nil) else { return }
let url = URL(fileURLWithPath: path)
do {
    self.alertSoundEffect = try AVAudioPlayer(contentsOf: url)
} catch let err {
    print("err: \(err)")
}

DispatchQueue.main.async {
    self.alertSoundEffect.numberOfLoops = -1
    self.alertSoundEffect.prepareToPlay()
    self.alertSoundEffect.play()
}

The fix online to declare the alertSoundEffect variable like this:

 private var alertSoundEffect : AVAudioPlayer!

has not worked at all.

I tried moving everything but the line:

self.alertSoundEffect.play()

to viewDidLoad as I thought maybe that code couldn't get called more than once, but it didn't help.

Specifically, the compiler highlights this line when it crashes:

self.alertSoundEffect = try AVAudioPlayer(contentsOf: url)

I tried using try AVAudioPlayer where it takes a Data object as a parameter or with including the type of audio file to be played, but that did not change anything.

When I try the AVAudioPlayer's delegate and declare it like this:

self.alertSoundEffect.delegate = self

right before the first lines of code I shared above Xcode highlights this line instead when it reliably crashes.

What else should I try?

michaeldebo
  • 3,065
  • 4
  • 14
  • 20

2 Answers2

0

I suppose your path is wrong. Try this:

guard let path = Bundle.main.path(forResource: "alert", ofType: "mp3") else { return }

Also, if your audio file is short, like less than 30s, then try not to call self.alertSoundEffect.prepareToPlay(). Just call self.alertSoundEffect.play() right away.

Since iOS 13, this was causing a bug in my app, since I have notification sounds which are 3-10 seconds long.

Starsky
  • 1,829
  • 18
  • 25
0

If you initialise your AVAudioPlayer like var wrongMusicPlayer: AVAudioPlayer = AVAudioPlayer() OR wrongMusicPlayer = AVAudioPlayer() in any method then please remove it and just Declare like var wrongMusicPlayer: AVAudioPlayer!.

iOS 13.1 Crash in AVAudio Player