简体   繁体   中英

Objective-C: To mute/unmute audio while recording video using AVFoundation on iOS

I am using the sample provided by Apple at this link to record and save video recording.

Wanted the ability to mute and un-mute audio before recording the video.

On Objective-C, I tried the belowmentioned code to mute/unmute on button click before starting video recording. But the video is getting recorded with the audio.

Tried without calling the beginConfiguration and commitConfiguration on the session object but still issue exists.

Any idea how to handle the same in Objective-C ?

- (IBAction)muteAudio:(id)sender
{

    self.muteAudio = !self.muteAudio;

    NSError *error = nil;

    [self.session beginConfiguration];

    if(self.muteAudio == FALSE)
    {

        // Add audio input.
        AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
        AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
        if ( ! audioDeviceInput ) {
            NSLog( @"Could not create audio device input: %@", error );
        }
        if ( [self.session canAddInput:audioDeviceInput] ) {
            [self.session addInput:audioDeviceInput];
        }
        else {
            NSLog( @"Could not add audio device input to the session" );
        }
    }
    else
    {

        // Add audio input.
        AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
        AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
        if ( ! audioDeviceInput ) {
            NSLog( @"Could not create audio device input: %@", error );
        }
        [self.session removeInput:audioDeviceInput];


    }
    [self.session commitConfiguration];
}

Found the solution. Add the below-mentioned code in the toggleMovieRecording method which will get called when you hit the record button.

    AVCaptureConnection *audioConnection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeAudio];
    audioConnection.enabled = !self.muteAudio;

The method after adding the logic to disable/enable audio.

- (IBAction)toggleMovieRecording:(id)sender
{
    /*
        Disable the Camera button until recording finishes, and disable
        the Record button until recording starts or finishes.

        See the AVCaptureFileOutputRecordingDelegate methods.
     */
    self.cameraButton.enabled = NO;
    self.recordButton.enabled = NO;
    self.captureModeControl.enabled = NO;

    /*
        Retrieve the video preview layer's video orientation on the main queue
        before entering the session queue. We do this to ensure UI elements are
        accessed on the main thread and session configuration is done on the session queue.
    */
    AVCaptureVideoOrientation videoPreviewLayerVideoOrientation = self.previewView.videoPreviewLayer.connection.videoOrientation;

    dispatch_async( self.sessionQueue, ^{
        if ( ! self.movieFileOutput.isRecording ) {
            if ( [UIDevice currentDevice].isMultitaskingSupported ) {
                /*
                    Setup background task.
                    This is needed because the -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:]
                    callback is not received until AVCam returns to the foreground unless you request background execution time.
                    This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded.
                    To conclude this background execution, -[endBackgroundTask:] is called in
                    -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:] after the recorded file has been saved.
                */
                self.backgroundRecordingID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
            }

            // Update the orientation on the movie file output video connection before starting recording.
            AVCaptureConnection *movieFileOutputConnection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
            movieFileOutputConnection.videoOrientation = videoPreviewLayerVideoOrientation;


            //Code to enable and disable audio in the recorded video file.
            AVCaptureConnection *audioConnection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeAudio];
            audioConnection.enabled = !self.muteAudio;


            // Start recording to a temporary file.
            NSString *outputFileName = [NSUUID UUID].UUIDString;
            NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[outputFileName stringByAppendingPathExtension:@"mov"]];
            [self.movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputFilePath] recordingDelegate:self];
        }
        else {
            [self.movieFileOutput stopRecording];
        }
    } );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM