title: Video recording in iOS programmatically
body: <p>I am trying to implement functionality like below </p>
  
  <p><strong>Final Recorded Video</strong> = "<strong>Capture a video from front camera</strong> + <strong>Record an audio from video</strong> (<em>which I am playing through video player</em>)".</p>
  
  <p>For more understanding please see the attach screen shot.</p>
  
  <p><img src="https://i.stack.imgur.com/zbCdI.png" alt="enter image description here"></p>
  
  <p>Using my blocks of codes which is given below: <strong>At the end what I get is A video but without audio.</strong> </p>
  
  <p>But what I want to trying to implement is "<strong>Final recorded video</strong> which must be <strong>combination</strong> of: '<strong>A video which is captured from my front camera</strong> + <strong>Record only audio from video file which I am playing</strong>.'"</p>
  
  <p>How can I achieve above functionality?</p>
  
  <p>This is my code.</p>
  
  <p>"<strong>Recording</strong>" Button Click Method is as following:</p>
  
  <pre><code>-(void) startRecording
  {
      [self initCaptureSession];
  
      NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                           pathForResource:@"video"
                                           ofType:@"mp4"]];
      [self playMovieAtURL:url];
  
      [self startVideoRecording];
  }
  </code></pre>
  
  <p>"<strong>initCaptureSession</strong>" : Using this method I am recording a video using front camera using 
  "AVCaptureSession"</p>
  
  <pre><code>-(void) initCaptureSession
  {
      NSLog(@"Setting up capture session");
      captureSession = [[AVCaptureSession alloc] init];
  
      NSLog(@"Adding video input");
  
      AVCaptureDevice *VideoDevice = [self frontFacingCameraIfAvailable];
  
      if (VideoDevice)
      {
          NSError *error;
          videoInputDevice = [AVCaptureDeviceInput deviceInputWithDevice:VideoDevice error:&amp;error];
          if (!error)
          {
              if ([captureSession canAddInput:videoInputDevice])
              {
                  [captureSession addInput:videoInputDevice];
              }
              else
              {
                  NSLog(@"Couldn't add video input");
              }
          }
          else
          {
              NSLog(@"Couldn't create video input");
          }
      }
      else
      {
          NSLog(@"Couldn't create video capture device");
      }
  
  
      NSLog(@"Adding audio input");
      AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeMuxed];
      NSError *error = nil;
      AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&amp;error];
      if (audioInput)
      {
          [captureSession addInput:audioInput];
      }
  
  
      NSLog(@"Adding movie file output");
      movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
  
      movieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024;    //&lt;&lt;SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME
  
      if ([captureSession canAddOutput:movieFileOutput])
          [captureSession addOutput:movieFileOutput];
  
      [self CameraSetOutputProperties];           //(We call a method as it also has to be done after changing camera)
  
      NSLog(@"Setting image quality");
      [captureSession setSessionPreset:AVCaptureSessionPresetMedium];
      if ([captureSession canSetSessionPreset:AVCaptureSessionPreset640x480])     //Check size based configs are supported before setting them
          [captureSession setSessionPreset:AVCaptureSessionPreset640x480];
  
      [captureSession startRunning];
  }
  
  - (void) CameraSetOutputProperties
  {
      AVCaptureConnection *CaptureConnection = nil;
  
      NSComparisonResult order = [[UIDevice currentDevice].systemVersion compare: @"5.0.0" options: NSNumericSearch];
      if (order == NSOrderedSame || order == NSOrderedDescending) {
          // OS version &gt;= 5.0.0
          CaptureConnection = [movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
      } else {
          // OS version &lt; 5.0.0
          CaptureConnection = [self connectionWithMediaType:AVMediaTypeVideo fromConnections:[movieFileOutput connections]];
      }
  
      //Set landscape (if required)
      if ([CaptureConnection isVideoOrientationSupported])
      {
          AVCaptureVideoOrientation orientation =  AVCaptureVideoOrientationPortrait;// AVCaptureVideoOrientationLandscapeRight;      //&lt;&lt;&lt;&lt;&lt;SET VIDEO ORIENTATION IF LANDSCAPE
          [CaptureConnection setVideoOrientation:orientation];
      }
   }
  </code></pre>
  
  <p>"<strong>-(void) playMovieAtURL: (NSURL*) theURL</strong> " By using this method I am playing a video </p>
  
  <pre><code>-(void) playMovieAtURL: (NSURL*) theURL
  {
  player =
  [[MPMoviePlayerController alloc] initWithContentURL: theURL];
  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
  
  player.scalingMode = MPMovieScalingModeAspectFill;
  player.controlStyle = MPMovieControlStyleNone;
  [player prepareToPlay];
  
  [[NSNotificationCenter defaultCenter]
   addObserver: self
   selector: @selector(myMovieFinishedCallback:)
   name: MPMoviePlayerPlaybackDidFinishNotification
   object: player];
  player.view.frame=CGRectMake(10, 30, 300, 200);
  [self.view addSubview:player.view];
  
  [player play];
  }
  </code></pre>
  
  <p>"<strong>startVideoRecording</strong>" using this method I have started recording the Final video.</p>
  
  <pre><code>- (void) startVideoRecording
  {
      //Create temporary URL to record to
      NSString *outputPath = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), @"output.mov"];
      NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
      NSFileManager *fileManager = [NSFileManager defaultManager];
      if ([fileManager fileExistsAtPath:outputPath])
      {
          NSError *error;
          if ([fileManager removeItemAtPath:outputPath error:&amp;error] == NO)
          {
              //Error - handle if required
              NSLog(@"file remove error");
          }
      }
      //Start recording
      [movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
  }
  
  - (void)captureOutput:(AVCaptureFileOutput *)captureOutput
  didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
        fromConnections:(NSArray *)connections
                  error:(NSError *)error
  {
      NSLog(@"didFinishRecordingToOutputFileAtURL - enter");
  
      BOOL RecordedSuccessfully = YES;
      if ([error code] != noErr)
      {
          // A problem occurred: Find out if the recording was successful.
          id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
          if (value)
          {
              RecordedSuccessfully = [value boolValue];
          }
      }
      if (RecordedSuccessfully)
      {
          //----- RECORDED SUCCESSFULLY -----
          NSLog(@"didFinishRecordingToOutputFileAtURL - success");
          ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
          if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputFileURL])
          {
              [library writeVideoAtPathToSavedPhotosAlbum:outputFileURL
                                          completionBlock:^(NSURL *assetURL, NSError *error)
               {
                   if (error)
                   {
                       NSLog(@"File save error");
                   }
                   else
                   {
                       recordedVideoURL=assetURL;
                   }
               }];
          }
          else
          {
              NSString *assetURL=[self copyFileToDocuments:outputFileURL];
              if(assetURL!=nil)
              {
                  recordedVideoURL=[NSURL URLWithString:assetURL];
              }
          }
      }
  }
  </code></pre>