swiftdisconnectavaudioengineavaudioplayernode

Swift: disconnect an AVAudioUnit from playing AVAudioEngine


I am playing an audio file with some effects, at some point. Here is the code:

 engine = AVAudioEngine()
    playerB = AVAudioPlayerNode()

    playerB.volume = 0.5

    let path = Bundle.main.path(forResource: "ukulele", ofType: "wav")!
    let url = NSURL.fileURL(withPath: path)

    let file = try? AVAudioFile(forReading: url)
    buffer = AVAudioPCMBuffer(pcmFormat: file!.processingFormat, frameCapacity: AVAudioFrameCount(file!.length))!
    try! file!.read(into: buffer)

    reverb.loadFactoryPreset(AVAudioUnitReverbPreset.cathedral)
    reverb.wetDryMix = 50

    distortion.loadFactoryPreset(AVAudioUnitDistortionPreset.speechRadioTower)
    distortion.wetDryMix = 25

    let delay = AVAudioUnitDistortion()
    delay.loadFactoryPreset(AVAudioUnitDistortionPreset.speechAlienChatter)
    delay.wetDryMix = 25


    engine.attach(playerB)
    engine.attach(reverb)
    engine.attach(distortion)
    engine.attach(delay)
    engine.attach(pitch)
    engine.attach(speedControl)

    engine.connect(playerB, to: pitch, format: nil)

    engine.connect(pitch, to: speedControl, format: nil)
    engine.connect(speedControl, to: reverb, format: nil)

    engine.connect(reverb, to: distortion, format: nil)
    engine.connect(distortion, to: engine.mainMixerNode, format: buffer.format)

    playerB.scheduleBuffer(buffer, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)



    engine.prepare()
    try! engine.start()

what I want is to disconnect one of the AVAudioUnit when a specific action occurs. However, after removing the AVAudioUnit the player is completely silent.

for example, if I want to remove reverb the code is: engine.disconnectNodeOutput(reverb) but after this line run, the player is silent.

What is the wrong thing I am doing? I simply want to remove one of the effects that was already added.


Solution

  • It’s a chain and you broke one of the links. Here’s your code:

    engine.connect(pitch, to: speedControl, format: nil)
    engine.connect(speedControl, to: reverb, format: nil)
    engine.connect(reverb, to: distortion, format: nil)
    engine.connect(distortion, to: engine.mainMixerNode, format: buffer.format)
    

    If you remove reverb node, there is now a hole between speed control and distortion. Nothing can cross that hole. You need to connect them.