Search code examples
swiftavaudioplayercore-audiowatchosavaudioplayernode

AVAudioPlayerNode.play() causes crash after backgrounding and foregrounding the app


I'm working on a watchOS app which plays sound using an AVAudioPlayerNode. Whenever I put the app in the background, open it back again and try to play sound, the app crashes with the following message:

Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'player did not see an IO cycle.'

If I use this answer to catch NSExceptions in Swift, the following error appears:

The operation couldn’t be completed. (com.apple.coreaudio.avfaudio error 0.)


Solution

  • Observe WKExtension.applicationDidBecomeActiveNotification.

    Whenever it gets posted:

    • reinitialize the AVAudioEngine instance you're using (audioEngine = AVAudioEngine())
    • reattach all the nodes