I just switched from AVAudio to AudioKit. To get things working I had to enable background audio and since then battery usage is woeful.
What is the best way to clean up and come out of background audio once a sequence or player has come to and end?
Any help would be greatly appreciated.
In your app delegate:
func applicationDidEnterBackground(_ application: UIApplication) {
    conductor.checkIAAConnectionsEnterBackground()
}
func applicationWillEnterForeground(_ application: UIApplication) {
    conductor.checkIAAConnectionsEnterForeground()
}
In your audio engine, or conductor (as per other AudioKit examples) do:
var iaaTimer: Timer = Timer()
func checkIAAConnectionsEnterBackground() {
    if let audiobusClient = Audiobus.client {
        if !audiobusClient.isConnected && !audiobusClient.isConnectedToInput {
            deactivateSession()
            AKLog("disconnected without timer")
        } else {
            iaaTimer.invalidate()
            iaaTimer = Timer.scheduledTimer(timeInterval: 20 * 60,
                                            target: self,
                                            selector: #selector(self.handleConnectionTimer),
                                            userInfo: nil, repeats: true)
        }
    }
}
func checkIAAConnectionsEnterForeground() {
    iaaTimer.invalidate()
    startEngine()
}
func deactivateSession() {
    stopEngine()
    do {
        try AKSettings.session.setActive(false)
    } catch let error as NSError {
        AKLog("error setting session: " + error.description)
    }
    iaaTimer.invalidate()
    AKLog("disconnected with timer")
}
@objc func handleConnectionTimer() {
    AKLog("should disconnect with timer")
    deactivateSession()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With