записывать и сохранять видео с помощью камеры avfoundation - PullRequest
0 голосов
/ 05 января 2020

Мой быстрый код ниже использует uiview для камеры. У меня есть 2 кнопки «Пуск» и «Стоп». В кнопке «Пуск» я хочу, чтобы пользовательский интерфейс начал запись видео, только если кнопка активирована. В игре «Стоп веселье» c я хочу, чтобы видео прекратило запись, а затем было добавлено и сохранено в фотогалерее как видео.

import UIKit;import AVFoundation



class ViewController: UIViewController, AVCapturePhotoCaptureDelegate {



    @IBOutlet var previewView : UIView!
    @IBOutlet var start : UIButton!
    @IBOutlet var stop : UIButton!


    var captureSession: AVCaptureSession!
    var stillImageOutput: AVCapturePhotoOutput!
    var videoPreviewLayer: AVCaptureVideoPreviewLayer!

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // Setup your camera here...
        captureSession = AVCaptureSession()
        captureSession.sessionPreset = .medium


        guard let backCamera = AVCaptureDevice.default(for: AVMediaType.video)
            else {
                print("Unable to access back camera!")
                return
        }

        do {
            let input = try AVCaptureDeviceInput(device: backCamera)
            //Step 9
            stillImageOutput = AVCapturePhotoOutput()
            stillImageOutput = AVCapturePhotoOutput()

            if captureSession.canAddInput(input) && captureSession.canAddOutput(stillImageOutput) {
                captureSession.addInput(input)
                captureSession.addOutput(stillImageOutput)
                setupLivePreview()
            }
        }
        catch let error  {
            print("Error Unable to initialize back camera:  \(error.localizedDescription)")
        }
    }

    func setupLivePreview() {

        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)

        videoPreviewLayer.videoGravity = .resizeAspect
        videoPreviewLayer.connection?.videoOrientation = .portrait
        previewView.layer.addSublayer(videoPreviewLayer)

        //Step12
        DispatchQueue.global(qos: .userInitiated).async { //[weak self] in
            self.captureSession.startRunning()
            //Step 13
            DispatchQueue.main.async {
                self.videoPreviewLayer.frame = self.previewView.bounds
            }
        }


    }

    @IBAction func take(_ sender: Any) {
        //start recording
        start.backgroundColor = .red
        stop.backgroundColor = .clear

    }

    @IBAction func save(_ sender: Any) {

        //stop recording and save to photogallery
        start.backgroundColor = .clear
        stop.backgroundColor = .red


    }




    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.captureSession.stopRunning()
    }

}
...