Swift:从播放AVAudioEngine断开AVAudioUnit的连接

时间:2019-05-14 06:52:36

标签: swift disconnect avaudioengine avaudioplayernode

在某些时候,我正在播放具有某些效果的音频文件。这是代码:

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

我想要的是在发生特定操作时断开AVAudioUnit之一。但是,在删除AVAudioUnit之后,播放器将完全保持静音。

例如,如果我要删除reverb,则代码为:engine.disconnectNodeOutput(reverb) 但在运行此行之后,播放器保持沉默。

我在做什么错了?我只想删除已经添加的一种效果。

1 个答案:

答案 0 :(得分:0)

这是一条链,您断开了其中一个链接。这是您的代码:

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)

如果删除混响节点,则速度控制和失真之间将出现一个漏洞。没有东西可以越过那个洞。您需要连接它们。