2

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.

mahdi
  • 149
  • 12

1 Answers1

0

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    so You mean every time I want to remove an effect, I should reconnect all the chain? But this way I can't continue playing the audio. It will: stop playing, instantiate the connections again, play the audio again. This way I'll hear the disconnection/connection of the audio, is there any other way? – mahdi May 14 '19 at 07:09
  • Connect them first. – matt May 14 '19 at 07:19
  • 1
    whenever I `engine.connect(pitch, to: speedControl, format: nil) engine.connect ... ` the player stops playing – mahdi May 14 '19 at 07:30