How to reconnect AKPlayer and AKMixer after AudioKit.stop()

一世执手 提交于 2021-01-27 11:30:09

问题


After calling AudioKit.stop(), and then subsequently calling AudioKit.start(), I'm unable to reconnect my AKMixer/AKPlayer to AudioKit. It appears that the engine starts successfully but no sound is produced when I call player.play(). I'm not quite sure what I'm missing. I've boiled it all down to a simple demo project and I've included the most important sections of code below.

View controller

class ViewController: UIViewController {

    public let tickSound = MySound(url: "tick.wav")

    @IBAction func stopAudioKit(_ sender: Any) {
        try! AudioKit.stop()
        print("AudioKit stopped")
    }

    @IBAction func playSound(_ sender: Any) {
        tickSound.play()
    }
}

Sound Object

class MySound: NSObject {
    private static var mixer: AKMixer = AKMixer()

    private var player: AKPlayer?

    init(url: String) {
        super.init()
        if let file = try? AKAudioFile(readFileName: url) {
            self.player = AKPlayer(audioFile: file)
            self.player?.buffering = .always
            MySound.mixer.connect(input: self.player)
        }
    }

    func play() {
        if AudioKit.output !== MySound.mixer {
            AudioKit.output = MySound.mixer
        }

        if !AudioKit.engine.isRunning {
            do {
                try AudioKit.start()
            } catch {
                assert(false)
            }
        }

        if AudioKit.engine.isRunning {
            player?.play()
        } else {
            assert(false)
        }
    }

}

Github demo project: https://github.com/rednebmas/AudioKitDemo

Thank you!

来源:https://stackoverflow.com/questions/54741719/how-to-reconnect-akplayer-and-akmixer-after-audiokit-stop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!