AudioKit背景音频电池使用情况

时间:2018-07-06 14:49:47

标签: ios swift background audiokit

我刚刚从AVAudio切换到AudioKit。为了使事情正常进行,我必须启用背景音频,从那以后电池的使用就很糟糕。

一旦序列或播放器进入和结束,清理和退出背景音频的最佳方法是什么?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

在您的应用程序委托中:

func applicationDidEnterBackground(_ application: UIApplication) {
    conductor.checkIAAConnectionsEnterBackground()
}

func applicationWillEnterForeground(_ application: UIApplication) {
    conductor.checkIAAConnectionsEnterForeground()
}

在您的音频引擎或指挥(按照其他AudioKit示例)中:

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()
}