AudioKit Background Audio Battery Usage
Asked Answered
D

1

6

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.

Dwarf answered 6/7, 2018 at 14:49 Comment(2)
Is this related to programming after all?Pneumonectomy
Its definitely related to programming. There a few techniques to check if you can shut down the engine - see if any IAA is connected, for instance. I'll write a more general answer below as we are implementing some battery saving techniques in Synth One this weekend.Bandwagon
B
4

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()
}
Bandwagon answered 8/7, 2018 at 1:42 Comment(2)
Thanks for providing this guidance! Follow-up question: even if we aren't using AudioBus integration with our app which integrates AudioKit, would the above solution still be applicable? Also could you add some details around the purpose of using a timer to fire and check again in the future? Thank you!Rubeola
Absolutely, just don't do the IAA stuff you don't need - just manage the engine.Bandwagon

© 2022 - 2024 — McMap. All rights reserved.