13

I am setting a microphone on a AVCaptureSession and I am in need of a switch for the mic. How should I proceed with this? Do I really need to the captureSession?.removeInput(microphone), or is there an easies way?

let microphone = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)

        do {
            let micInput = try AVCaptureDeviceInput(device: microphone)
            if captureSession.canAddInput(micInput) {
                captureSession.addInput(micInput)
            }
        } catch {
            print("Error setting device audio input: \(error)")
            return false
        }
dre_84w934
  • 678
  • 8
  • 27
  • 1
    I have tried the removeInput() method but that creates a jerk in preview layer when again addInput() for microphone. Did you find any better solution than the accepted one? – Asif Bilal Mar 14 '19 at 13:41

2 Answers2

9

You can always just leave the mic input attached and then using your switch decide what to do with the audio buffer. If the switch is off then don't process the audio data. I found an objc.io article that talks about how to set up the separate audio and video buffers before writing the data with an AVAssetWriter.

Walter
  • 5,867
  • 2
  • 30
  • 43
  • 1
    You are right but I am using captureSession delegate method to start and stop recording. So, this solution doesn't work for me. – Asif Bilal Mar 14 '19 at 13:44
1

By default, all AVCaptureAudioChannel objects exposed by a connection are enabled. You may set enabled to false to stop the flow of data for a particular channel.

https://developer.apple.com/documentation/avfoundation/avcaptureaudiochannel/1388574-isenabled

Santosh Botre
  • 549
  • 5
  • 21