2

I created a custom camera, and I am trying to add a feature where users can switch between the front and back camera while recording a video.

But when trying to switch cameras, in the switch function the same pause and execute another video, not allowing me to get them together in a single file and play it at the end without cuts.

import UIKit
import AVFoundation
import CoreMedia

class VideoViewController: UIViewController, AVCaptureFileOutputRecordingDelegate,UITextFieldDelegate,UITextViewDelegate {

    @IBOutlet weak var previewView:UIView!
    @IBOutlet weak var recordButton: UIButton!
    @IBOutlet weak var toggleButton: UIButton!


    var captureSession = AVCaptureSession()
    var videoCaptureDevice:AVCaptureDevice?
    var previewLayer:AVCaptureVideoPreviewLayer?
    var movieFileOutput = AVCaptureMovieFileOutput()
    var outputFileLocation:URL?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.initializeCamera()

    }

    func dismissKeybord (){
    textView.resignFirstResponder()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillLayoutSubviews() {
        self.setVideoOrientation()
    }


    @IBAction func recordVideoButtonPressed(_ sender: AnyObject) {


        if self.movieFileOutput.isRecording {

            switchcamera = true

            self.movieFileOutput.stopRecording()

        } else {

            self.movieFileOutput.connection(withMediaType: AVMediaTypeVideo).videoOrientation = self.videoOrientation()

            self.movieFileOutput.maxRecordedDuration = self.maxRecordedDuration()

            self.movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath:self.videoFileLocation()), recordingDelegate: self)

        }

        self.updateRecordButtonTitle()

    }


    @IBAction func cameraTogglePressed(_ sender: AnyObject) {

        self.switchCameraInput()

    }


    @IBAction func btnGallery(_ sender: UIButton) {

        self.performSegue(withIdentifier: "videoPreview", sender: nil)

    }


    func initializeCamera(){

        self.captureSession.sessionPreset = AVCaptureSessionPresetHigh

        let discovery = AVCaptureDeviceDiscoverySession.init(deviceTypes: [AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified) as AVCaptureDeviceDiscoverySession

        for device in discovery.devices as [AVCaptureDevice] {

            if device.hasMediaType(AVMediaTypeVideo) {
                if device.position == AVCaptureDevicePosition.back {
                    self.videoCaptureDevice = device
                }
            }

        }

        if videoCaptureDevice != nil {
            do {
                try self.captureSession.addInput(AVCaptureDeviceInput(device: self.videoCaptureDevice))

                if let audioInput = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio) {
                    try self.captureSession.addInput(AVCaptureDeviceInput(device: audioInput))
                }

                self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)

                self.previewView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)

                self.previewView.layer.addSublayer(self.previewLayer!)
                self.previewLayer?.frame = self.previewView.frame

                self.setVideoOrientation()

                self.captureSession.addOutput(self.movieFileOutput)

                self.captureSession.startRunning()

            } catch {
                print(error)
            }
        }

    }

    //Orientation Camera Record
    func setVideoOrientation() {
        if let connection = self.previewLayer?.connection {
            if connection.isVideoOrientationSupported {
                connection.videoOrientation = self.videoOrientation()
                self.previewLayer?.frame = self.view.bounds
            }
        }
    }

    //Switch Camrea function

    func switchCameraInput() {

        self.captureSession.beginConfiguration()

        var existingConnection:AVCaptureDeviceInput!

        for connection in self.captureSession.inputs {
            let input = connection as! AVCaptureDeviceInput
            if input.device.hasMediaType(AVMediaTypeVideo) {
                existingConnection = input
            }

        }

        self.captureSession.removeInput(existingConnection)

        var newCamera:AVCaptureDevice!
        if let oldCamera = existingConnection {
            if oldCamera.device.position == .back {
                newCamera = self.cameraWithPosition(position: .front)
            } else {
                newCamera = self.cameraWithPosition(position: .back)
            }
        }

        var newInput:AVCaptureDeviceInput!

        do {
            newInput = try AVCaptureDeviceInput(device: newCamera)
            self.captureSession.addInput(newInput)
        } catch {
            print(error)
        }

        self.captureSession.commitConfiguration()
    }

    //Capture Function Archive Library

    func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {

        print("Finished recording: \(outputFileURL)")


        self.outputFileLocation = outputFileURL
        //self.performSegue(withIdentifier: "videoPreview", sender: nil)

    }

    // Video Orientation Record

    func videoOrientation() -> AVCaptureVideoOrientation {

        var videoOrientation:AVCaptureVideoOrientation!

        let orientation:UIDeviceOrientation = UIDevice.current.orientation

        switch orientation {
        case .portrait:
            videoOrientation = .portrait
        case .landscapeRight:
            videoOrientation = .landscapeLeft
        case .landscapeLeft:
            videoOrientation = .landscapeRight
        case .portraitUpsideDown:
            videoOrientation = .portraitUpsideDown
        default:
            videoOrientation = .portrait
        }

        return videoOrientation

    }

    //Video Save Temp Library

    func videoFileLocation() -> String {
        return NSTemporaryDirectory().appending("prompterFile.mov")
    }

    // Record Funcition

    func updateRecordButtonTitle() {

        var isRecording = false

        if !self.movieFileOutput.isRecording {

            isRecording = true

        } else {

            isRecording = false

            stopScrolling()

            //Open Button Gallery

            btnGallery.isHidden = false
        }
    }


    func maxRecordedDuration() -> CMTime {
        let seconds : Int64 = 300
        let preferredTimeScale : Int32 = 1
        return CMTimeMake(seconds, preferredTimeScale)
    }

    func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice?
    {
        let discovery = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified) as AVCaptureDeviceDiscoverySession
        for device in discovery.devices as [AVCaptureDevice] {
            if device.position == position {
                return device
            }
        }

        return nil
    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {


        let preview = segue.destination as! VideoPreviewViewController
        preview.fileLocation = self.outputFileLocation
    }

}
thedp
  • 8,350
  • 16
  • 53
  • 95
  • I might be wrong, but maybe it's not possible. What you could do is create a new file every time the user switches camera, and when done concat all the files into a single final file. – thedp Apr 25 '18 at 19:14
  • Hi TheDP, has some articles on this in stackoverflow but in Objective C, or those that are in Swift did not work. I'm a bit lazy on the subject, I'm trying but nothing. But all help and welcome! I'll try to merge the two videos thanks! – Wagner Filho Apr 25 '18 at 20:10
  • Checkout my answer: https://stackoverflow.com/a/56572852/7090286 – Woody Jean-louis Nov 26 '19 at 07:18

0 Answers0