Swift AVAudioEngine - How to mute local mic

Viewed 277

I'm using AVAudioEngine to get local mic input and then broadcast it. I want to stop getting local mic input when mute button is tapped.

I tried three things:

  1. audioEngine.inputNode.isVoiceProcessingInputMuted = true - It did not work.
  2. audioEngine.stop() - Actually it works but causes other problems: I'm using HaishinKit to stream screen-recording + mic-input + other device audio. Stopping the audioEngine causes small lag on viewer side.
  3. Mute using HaishinKit.RTMPStream: rtmpStream.audioSettings[.muted] = true - It works but mutes entire audio. I want to mute only local mic not other device audio.

//

private func startTappingMicrophone() {
    let inputNode = audioEngine.inputNode
    let inputFormat = inputNode.outputFormat(forBus: 0)
    audioEngine.inputNode.installTap(onBus: 0, bufferSize: AVAudioFrameCount(bufferSize), format: inputFormat) { [weak self] buffer, _ in
          guard let self = self else { return }
          self.conversionQueue.async {
            if let cmSampleBuffer = self.configureSampleBuffer(pcmBuffer: buffer) {
              self.delegate?.recievedRecordedFrame(cmSampleBuffer)
            }
          }
    }
    audioEngine.prepare()
    try? audioEngine.start()
}
1 Answers

Depending on your setup, it may help to simply not send buffers to the delegate.

But what will work either way is to zero the buffer:

if let floatChannelData = buffer.floatChannelData {
    for c in 0..<Int(buffer.format.channelCount) {
        memset(floatChannelData[c], 0, MemoryLayout<Float>.size * Int(buffer.frameLength))
    }
}
Related