允许 Swift 的背景音频不起作用

Allowing background audio with Swift not working

我想在应用未处于焦点时允许背景音频。我目前有这段代码,应该允许:

do {
    try AKSettings.setSession(category: .playback, with: .mixWithOthers)
} catch {
    print("error")
}
AKSettings.playbackWhileMuted = true

我还在功能设置中启用了设置 'Audio, Airplay and Picture in Picture'。但是,当我按下设备上的主页按钮时,音频不会继续播放。我究竟做错了什么?如果重要的话,我正在使用 AudioKit 来产生声音。

我正在使用一个单例来容纳我命名为 AudioPlayer.swift 的所有 AudioKit 组件。这是我的 AudioPlayer.swift 单例文件中的内容:

class AudioPlayer: NSObject {
    var currentFrequency = String()
    var soundIsPlaying = false

    var leftOscillator = AKOscillator()
    var rightOscillator = AKOscillator()

    var rain = try! AKAudioFile()
    var rainPlayer: AKAudioPlayer!

    var envelope = AKAmplitudeEnvelope()

    override init() {
        super.init()

        do {
            try AKSettings.setSession(category: .playback, with: .mixWithOthers)
        } catch {
            print("error")
        }
        AKSettings.playbackWhileMuted = true

        AudioKit.output = envelope
        AudioKit.start()
    }

    func setupFrequency(left: AKOscillator, right: AKOscillator, frequency: String) {
        currentFrequency = frequency

        leftOscillator = left
        rightOscillator = right

        let leftPanner = AKPanner(leftOscillator)
        leftPanner.pan = -1

        let rightPanner = AKPanner(rightOscillator)
        rightPanner.pan = 1

        //Set up rain and rainPlayer
        do { 
            rain = try AKAudioFile(readFileName: "rain.wav")
            rainPlayer = try AKAudioPlayer(file: rain, looping: true, deferBuffering: false, completionHandler: nil)
        } catch { print(error) }

        let mixer = AKMixer(leftPanner, rightPanner, rainPlayer)

        //Put mixer in sound envelope
        envelope = AKAmplitudeEnvelope(mixer)
        envelope.attackDuration = 2.0
        envelope.decayDuration = 0
        envelope.sustainLevel = 1
        envelope.releaseDuration = 0.2

        //Start AudioKit stuff
        AudioKit.output = envelope
        AudioKit.start()
        leftOscillator.start()
        rightOscillator.start()
        rainPlayer.start()
        envelope.start()
        soundIsPlaying = true
    }
}

这是我的一个音效视图控制器的示例,它引用 AudioKit 单例向它发送特定频率(我有大约十几个这样的视图控制器,每个都有自己的频率设置):

class CalmView: UIViewController {
    let leftOscillator = AKOscillator()
    let rightOscillator = AKOscillator()

    override func viewDidLoad() {
        super.viewDidLoad()

        leftOscillator.amplitude = 0.3
        leftOscillator.frequency = 220

        rightOscillator.amplitude = 0.3
        rightOscillator.frequency = 230
    }

    @IBAction func playSound(_ sender: Any) {
        if shared.soundIsPlaying == false {
            AudioKit.stop()
            shared.setupFrequency(left: leftOscillator, right: rightOscillator, frequency: "Calm")
        } else if shared.soundIsPlaying == true && shared.currentFrequency != "Calm" {
            AudioKit.stop()
            shared.leftOscillator.stop()
            shared.rightOscillator.stop()
            shared.rainPlayer.stop()
            shared.envelope.stop()
            shared.setupFrequency(left: leftOscillator, right: rightOscillator, frequency: "Calm")
        } else {
            shared.soundIsPlaying = false
            shared.envelope.stop()
        }
    }
}

我在 ViewController.swift 文件中实例化了 AudioPlayer 单例。

这取决于你什么时候开始配置AudioKit。如果您使用的是 AudioKit,您应该使用它的 AKSettings 来管理您的会话类别。基本上不仅是播放类还有mixWithOthers。默认情况下,这样做:

/// Set the audio session type
@objc open static func setSession(category: SessionCategory,
                            with options: AVAudioSessionCategoryOptions = [.mixWithOthers]) throws {

所以你会在 ViewController:

中做这样的事情
    do {
        if #available(iOS 10.0, *) {
            try AKSettings.setSession(category: .playAndRecord, with: [.defaultToSpeaker, .allowBluetooth, .allowBluetoothA2DP])
        } else {
            // Fallback on earlier versions
        }
    } catch {
        print("Errored setting category.")
    }

所以我认为这是一个直截了当的问题。设置应用程序间音频也可能有所帮助。如果您仍然遇到问题并提供更多信息,我可以提供更多帮助,但这是我根据您目前提供的信息所能收集到的最好的答案。