Sprite Kit & playing sound leads to app termination

Lior Pollak picture Lior Pollak · Sep 24, 2013 · Viewed 12.3k times · Source

using ARC

Just a problem I've run into- I have an SKScene in which I play a sound fx using SKAction class method

[SKAction playSoundFileNamed:@"sound.wav" waitForCompletion:NO];

Now when I try to go to background, no matter that the sound was over, apparently iOS is terminating my app due to gpus_ReturnNotPermittedKillClient.

Now only when I comment this line and not running the action iOS runs it great in background (of course, paused, but without termination).

What am I doing wrong?

EDIT: iOS will not terminate the app if the line wasn't run- say, if it was in an if statement that wasn't run (soundOn == YES) or something like that, when the bool is false

Answer

LearnCocos2D picture LearnCocos2D · Oct 10, 2013

The problem is AVAudioSession can't be active while the app enters background. This isn't immediately obvious because Sprite Kit makes no mention that it uses AVAudioSession internally.

The fix is quite simple, and also applies to ObjectAL => set the AVAudioSession to inactive while the app is in background, and reactivate the audio session when the app enters foreground.

A simplified AppDelegate with this fix looks like so:

#import <AVFoundation/AVFoundation.h>
...

- (void)applicationWillResignActive:(UIApplication *)application
{
    // prevent audio crash
    [[AVAudioSession sharedInstance] setActive:NO error:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // prevent audio crash
    [[AVAudioSession sharedInstance] setActive:NO error:nil];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // resume audio
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
}

PS: this fix will be included in Kobold Kit v7.0.3.