Search code examples
iosswiftavaudioplayerexc-bad-access

Re-Assigning instance of AVAudioPlayer in iOS13 leads to BAD_ACCESS runtime error


I have an app, that is for many years in the AppStore and runs without any crashes (last deployment target iOS 12.4). I have some code for playing a sound on certain events in the app.

Now I tried to upgrade my app for iOS 13 and without changing any code related to that “playSound” thing, I always get this runtime error, when testing on a real device. Does not happen on simulator.

Thread 1: EXC_BAD_ACCESS (code=1, address=0x48)Shows the error message

PLEASE: Before you mark that question as “duplicate”, consider that this must have something to do with the release of iOS13, because before it didn’t happen and the code is just "usual".

Here is my code, also on gitHub.

I have a property in my ViewController to prevent ARC deallocating my AVAudioPlayer:

private var mySoundPlayer: AVAudioPlayer = AVAudioPlayer()

I have a routine, where the “play sound” should be performed (here happens the error, when assigning a new instance of AVAudioPlayer. The resourceURL is not the problem, the RE-ASSIGNING is the problem, I tested it with a new instance not being assigned and i did not crash.

// -------------------------------------------------
// MARK: Private Methods
// -------------------------------------------------

private func makeSoundEvent(_ soundEvent : SoundEvent) {
    
    guard Settings().getSound() == .soundON else { return }
    guard let urlToRessource : URL = soundEvent.getFileURLToSoundRessource() else { return }
    do {
        mySoundPlayer = try AVAudioPlayer(contentsOf: urlToRessource)
        try? AVAudioSession.sharedInstance().setActive(true)
        mySoundPlayer.play()
    }
    catch { print("Could not create AVPlayer for ressource \(urlToRessource)") }
}

And here I have the call of that subroutine, somewhere in my viewDidLoad() with a delay of 2 seconds.

DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
    self.makeSoundEvent(.startFanfare)
}

I think it somehow does not work because of the async thread. But since it is on the main thread, I thought this should work.


Solution

  • Just remove the initialisation and it will work

    private var mySoundPlayer: AVAudioPlayer!
    

    Cheers!!!