1
votes

I want my background song to stop playing when music from another app is playing. Such as apple music or Spotify. If you download color switch you'll know what I mean. Currently Im using the method below but my background song doesn't stop it mixes with the playing music.(This method kinda works with apple music but not Spotify). I want my song to play indefinitely until other music is playing in background and for it to start again when the other music is paused.(Try it with color Switch)

Thanks

 func setUpAudio() {
        //dead = SKAction.playSoundFileNamed(SoundFile.dead, waitForCompletion: true)
       // buttonpress = SKAction.playSoundFileNamed(SoundFile.button, waitForCompletion: true)

        if GameScene.backgroundMusicPlayer == nil {
            let backgroundMusicURL = Bundle.main.url(forResource: SoundFile.BackgroundMusic, withExtension: nil)

            do {
                let theme = try AVAudioPlayer(contentsOf: backgroundMusicURL!)
                GameScene.backgroundMusicPlayer = theme

            } catch {
                // couldn't load file :[
            }

            GameScene.backgroundMusicPlayer.numberOfLoops = -1
        }

        if !GameScene.backgroundMusicPlayer.isPlaying {
            GameScene.backgroundMusicPlayer.play()
        }
        let audioSession = AVAudioSession.sharedInstance()

        /*try!audioSession.setCategory(AVAudioSessionCategoryAmbient, with: AVAudioSessionCategoryOptions.mixWithOthers
        )*/

        do { try!audioSession.setCategory(AVAudioSessionCategoryAmbient)
        try AVAudioSession.sharedInstance().setActive(true) }
        catch let error as NSError { print(error) }
        //s audio from other sessions to be ducked (reduced in volume) while audio from this session plays
    }
2

2 Answers

2
votes

You're session category allows mixing, which is not what you want. Try using AVAudioSessionCategoryPlayback or AVAudioSessionCategorySoloAmbient, as these won't allow your app to mix audio with other apps.

See the docs for more info

1
votes

You will need to set the AVAudioSession to active.

    let _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    let _ = try? AVAudioSession.sharedInstance().setActive(true)