Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AudioKit Background Audio Battery Usage

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.

like image 890
Mirkin Avatar asked Jul 06 '18 14:07

Mirkin


1 Answers

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()
}
like image 96
Aurelius Prochazka Avatar answered Oct 06 '22 18:10

Aurelius Prochazka