Switching from the rear camera to the front camera while recording

So, I have a custom camera that works fully. You can record a video and get a file, etc. You can choose which camera you would like to use; front or back. However, I would like, when I click on the recording, that I can switch between the front camera and the rear camera, and it is still being written to the file until I press stop recording. Hope this makes sense.

My code for switching cameras:

@IBAction func changeCamera(sender: AnyObject) {

    println("change camera")

    self.recordButton.enabled = false

    dispatch_async(self.sessionQueue!, {

        var currentVideoDevice:AVCaptureDevice = self.videoDeviceInput!.device
        var currentPosition: AVCaptureDevicePosition = currentVideoDevice.position
        var preferredPosition: AVCaptureDevicePosition = AVCaptureDevicePosition.Unspecified

        switch currentPosition{
        case AVCaptureDevicePosition.Front:
            preferredPosition = AVCaptureDevicePosition.Back
        case AVCaptureDevicePosition.Back:
            preferredPosition = AVCaptureDevicePosition.Front
        case AVCaptureDevicePosition.Unspecified:
            preferredPosition = AVCaptureDevicePosition.Back

        }



        var device:AVCaptureDevice = ViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: preferredPosition)

        var videoDeviceInput: AVCaptureDeviceInput = AVCaptureDeviceInput(device: device, error: nil)

        self.session!.beginConfiguration()

        self.session!.removeInput(self.videoDeviceInput)

        if self.session!.canAddInput(videoDeviceInput){

            NSNotificationCenter.defaultCenter().removeObserver(self, name:AVCaptureDeviceSubjectAreaDidChangeNotification, object:currentVideoDevice)

            ViewController.setFlashMode(AVCaptureFlashMode.Auto, device: device)

            NSNotificationCenter.defaultCenter().addObserver(self, selector: "subjectAreaDidChange:", name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: device)

            self.session!.addInput(videoDeviceInput)
            self.videoDeviceInput = videoDeviceInput

        }else{
            self.session!.addInput(self.videoDeviceInput)
        }

        self.session!.commitConfiguration()



        dispatch_async(dispatch_get_main_queue(), {
            self.recordButton.enabled = true
            self.stopRecording.enabled = true
        })

    })

}
+4
source share

All Articles