使用 AVAudioSession 时背景音频安静

Background Audio quiet when using AVAudioSession

我正在尝试重现 snapchat 对音乐等背景音频的影响。进入他们的应用程序时,即使在录音时,它也会保持正常音量。在我的应用程序中,它在打开应用程序时几乎立即变得安静。

我试过在 AVAudioSession 设置类别功能中使用 .mixWithOthers 和 .defaultToSpeaker 选项。这些没有区别。

            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")

        }

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

可能是因为您在打开应用程序后立即配置和激活音频会话?如果那是问题所在,请不要那样做。仅在您真正需要之前配置和激活音频会话。例如,在用户真正要求开始录制之前不要调整音频会话。 可以根据需要在应用的整个生命周期内更改音频会话类别。