4

I want my SpriteKit game not to interrupt background music that user listens (Music.app or radio app).

Everything goes fine until execution reaches this line:

sSharedShootSoundAction = [SKAction playSoundFileNamed:@"plane_shoot.aiff" 
                                     waitForCompletion:NO];

After this line background music stops. How to avoid this?

Andrey Gordeev
  • 30,606
  • 13
  • 135
  • 162

2 Answers2

7

I have also encountered this problem myself. FYI my solutions are in swift so just translate this to Objective C if you are still using that.

For me my solution included two parts. First, I had to initialize my SoundAction SKAction within my didMoveToView function in my scene file. So your scene file should look something like this:

import SpriteKit
import GameKit
import AVFoundation

class GameScene: SKScene, SKPhysicsContactDelegate {
    
    var sSharedShootSoundAction: SKAction = SKAction()

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        sSharedShootSoundAction = SKAction.playSoundFileNamed("plane_shoot.aiff", waitForCompletion: false)
    }

}

Then in your AppDelegate file you need to place the following line of code in your application didFinishLaunchingWithOptions function. (DO NOT FORGET TO IMPORT AVFOUNDATION IN YOUR APPDELEGATE). So your app delegate method should like something like this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    // INSERT THIS LINE BELOW.
    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)

    return true
}

with Swift 4:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryAmbient)
    }catch{
        // handle error
        print("error setting category of audio session")
    }
    return true
}

Hope this solves it for you as it did for me! Let me know if it doesn't.

DanielZanchi
  • 2,708
  • 1
  • 25
  • 37
raynertanxw
  • 83
  • 1
  • 9
0

Update for Swift 5, Xcode 11: Put this into AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    // Below line will set all app sounds as ambient
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)

    return true
}
xellos
  • 11
  • 2