I'm trying to reproduce the effects snapchat has with background audio like music. When entering their app it stays at normal volume, even when recording. In my app it gets almost silent immediately upon opening the app.

I've tried using the .mixWithOthers, and .defaultToSpeaker options in AVAudioSession set category function. These make no difference.

            if #available(iOS 10.0, *) {
                try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.mixWithOthers, .allowBluetooth, .allowAirPlay, .allowBluetoothA2DP, .defaultToSpeaker])
            } else {
                let options: [AVAudioSession.CategoryOptions] = [.mixWithOthers, .allowBluetooth, .defaultToSpeaker]
                              let category = AVAudioSession.Category.playAndRecord
                let selector = NSSelectorFromString("setCategory:withOptions:error:")
                AVAudioSession.sharedInstance().perform(selector, with: category, with: options)
            }
            try AVAudioSession.sharedInstance().setActive(true)
            session.automaticallyConfiguresApplicationAudioSession = false
        }
        catch {
            print("Failed to set background audio preference")

        }

1 Answers

0
matt On Best Solutions

In my app it gets almost silent immediately upon opening the app.

Perhaps that is because you are configuring and activating the audio session immediately upon opening the app? If that’s the problem, don’t do that. Configure and activate the audio session only just before you really need to. For example, don't tweak the audio session until the user actually asks to start recording. It is fine to change the audio session category, as needed, throughout the lifetime of your app.