iosswiftavcapturesessionavcapturemoviefileoutput

how to extract the video from the capture session using the delegate method?


I'm trying to learn how camera works in swift, so I created a simple viewController set the session, the input and output instances, and then I start recording, but the lenght of the video is always zero and the AVCaptureOutput.isRunning is always false... here's my code

class cameraViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

    let recordButton: UIButton = {
        let button = UIButton()
        button.layer.cornerRadius = 30
        button.backgroundColor = UIColor.black
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(startRecording), for: UIControl.Event.touchUpInside)
        return button
    }()

    let session = AVCaptureSession()
    lazy var previewLayer = AVCaptureVideoPreviewLayer(session: session)


    override func viewDidLoad() {
        super.viewDidLoad()
        previewLayer.frame = view.frame
        view.layer.addSublayer(previewLayer)
        setUpSession()
        setUpViewsAndConstraints()
    }


    func setUpViewsAndConstraints(){
        view.addSubview(recordButton)

        recordButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        recordButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -80).isActive = true
        recordButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
        recordButton.heightAnchor.constraint(equalToConstant: 60).isActive = true


    }

    @objc func startRecording(button: UIButton){
        let url = Bundle.main.bundleURL
        let output = (session.outputs[0] as! AVCaptureMovieFileOutput)
        print(output.isRecording)

        if output.isRecording == false {
            print("recording is about to start")
            output.startRecording(to: url, recordingDelegate: self)
        } else {
            print("recording is about to stop")
            output.stopRecording()
        }
    }


    func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
        print("recorded duration:",output.recordedDuration)
    }


    func setUpSession(){
        session.beginConfiguration()

        // setting devices and inputs

        guard let device = AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInDualCamera, for: AVMediaType.video, position: AVCaptureDevice.Position.unspecified) else {return}
        guard let input = try? AVCaptureDeviceInput(device: device) else {print("input failed");return}
        session.addInput(input)

        // setting outputs...

        let videoOutput = AVCaptureMovieFileOutput()
        session.sessionPreset = AVCaptureSession.Preset.high
        session.addOutput(videoOutput)
        session.commitConfiguration()
        session.startRunning()
    }

}

I can see the input video from camera on my view layer normally, but when I hit the record button nothing seems to work, the delegate method prints right away that the recorded duration is zero, and the @objc func startRecording(button: UIButton) never prints out "recording is about to stop" but always "recording is about to start"..

and which url should I put on the method output.startRecording(to: url, recordingDelegate: self)? I was a bit confused once the data goes to delegate method why do I need to specify this URL what should I put in there?

what am I missing here?

thank you in advance for the answer!!


Solution

  • Here

    output.startRecording(to: url, recordingDelegate: self)
    

    you should put url of the output video , and since you set it to

    let url = Bundle.main.bundleURL
    

    that can't write in main bundle , so recording doesn't start , you can verify that by checking the printed error

    func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
        print(error)
    }
    

    you need to create a url say in document and supply it

     let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 
     let completeMovie = URL(fileURLWithPath: documentsURL.path).appendingPathComponent("video.mp4")