Search code examples
audiokit

AudioKit 5 - player started when in a disconnected state


Trying to use AudioKit 5 to dynamically create a player with a mixer, and attach it to a main mixer. I'd like the resulting chain to look like:

AudioPlayer -> Mixer(for player) -> Mixer(for output) -> AudioEngine.output

My example repo is here: https://github.com/hoopes/AK5Test1

You can see in the main file here (https://github.com/hoopes/AK5Test1/blob/main/AK5Test1/AK5Test1App.swift) that there are three functions.

The first works, where an mp3 is played on a Mixer that is created when the controller class is created.

The second works, where a newly created AudioPlayer is hooked directly to the outputMixer.

However, the third, where I try to set up the chain above, does not, and crashes with the "player started when in a disconnected state" error. I've copied the function here:

/** Try to add a mixer with a player to the main mixer */
func doesNotWork() {
    let p2 = AudioPlayer()
    let localMixer = Mixer()
        
    localMixer.addInput(p2)
    outputMixer.addInput(localMixer)
        
    playMp3(p: p2)
}

Where playMp3 just plays an example mp3 on the AudioPlayer.

I'm not sure how I'm misusing the Mixer. In my actual application, I have a longer chain of mixers/boosters/etc, and getting the same error, which led me to create the simple test app.

If anyone can offer advice, I'd love to hear it. Thanks so much!


Solution

  • The advice I wound up getting from an AudioKit contributor was to do everything possible to create all audio objects that you need up front, and dynamically change their volume to "connect" and "disconnect", so to speak.

    Imagine you have a piano app (a contrived example, but hopefully gets the point across) - instead of creating a player when a key is pressed, connecting it, and disconnecting/disposing when the note is complete, create a player for every key on startup, and deal with them dynamically - this prevents any weirdness with "disconnected state", etc.

    This has been working pretty flawlessly for me since.