AVCaptureSession: Add / Remove DeviceInput

I am trying to implement a function in which you can enable or disable the microphone during AVCaptureSession. This is how I turn on the device (initialization)

-(void)initMicrophoneInput:(AVCaptureSession*)session{
    AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    _microphoneInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioDevice error:nil];
    if ([session canAddInput:_microphoneInput]){
        [session addInput:_microphoneInput];
    } else {
        NSLog(@"can't add input");
    }
}

And this is my mute / unmute function:

- (IBAction)manageMicrophone:(id)sender {
    [_captureSession beginConfiguration];
    if(_microphoneMuted == NO){
        [_captureSession removeInput:_microphoneInput];
    }else{
        [self initMicrophoneInput:_captureSession];
    }
    [_captureSession commitConfiguration];
    _microphoneMuted = !_microphoneMuted;
}

Initializing and removing the microphone work well, but then I can’t turn on the microphone again. My _captureSession.inputs contain a micro device, but I no longer get audio samples from- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection;

+5
source share

All Articles