0

I have a problem with AVAudioEngine in SpriteKit game - when plugging/unplugging of headphones the engine stops and when the next sound play the app crashes. It is a known bug (or feature?) - with a suggestion to fix it - to use notification center, AVAudioEngine should post notification when it is changing it's states. I have made this code:

let notificationName = Notification.Name("AVAudioEngineConfigurationChange")      

NotificationCenter.default.addObserver(self, selector: #selector(self.restartEngine(notification:)), name: notificationName, object: nil)

When I do this:

NotificationCenter.default.post(name: notificationName, object: nil)

My selector gets called. However when I plug/unplug headphones - nothing happens. Swift 3, xcode 8, iOS 9.3 Any suggestions on how to fix it?

1 Answers1

0

The original Cocoa name of the notification is AVAudioEngineConfigurationChangeNotification, but the Swift constant is called AVAudioEngineConfigurationChange. Therefore you can handle the notification by using either:

let notificationName = Notification.Name("AVAudioEngineConfigurationChangeNotification")

or

let notificationName = Notification.Name.AVAudioEngineConfigurationChange

Your selector should then be called when plugging-in/unplugging headphones.

This appears to only be a partial solution for SpriteKit audio flakiness. I tried the following inside the notification handler:

try? self.audioEngine.start() 

I was able to stop the crash, but my SKAudioNode wouldn't make any sound after the plug/unplug event, until the process was restarted.

Martin Kenny
  • 2,468
  • 1
  • 19
  • 16