Swift 使用与拍照相同的方法录制视频

Swift record video using same method as taking photo

我目前正在使用以下代码允许用户拍照:

private func configurePhotoView() {
    capturedPhoto.contentMode = .ScaleAspectFill
    capturedPhoto.clipsToBounds = true
    capturedPhoto.hidden = true

    captureSession = AVCaptureSession()
    captureSession!.sessionPreset = AVCaptureSessionPresetPhoto

    photoCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    var error: NSError?
    photoDeviceInput = AVCaptureDeviceInput(device: photoCaptureDevice, error: &error)

    if error == nil && captureSession!.canAddInput(photoDeviceInput) {
        captureSession!.addInput(photoDeviceInput)

        stillImageOutput = AVCaptureStillImageOutput()
        stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
        if captureSession!.canAddOutput(stillImageOutput) {
            captureSession!.addOutput(stillImageOutput)

            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
            previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.Portrait
            cameraView.layer.addSublayer(previewLayer)

            captureSession!.startRunning()

            self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "focusPhoto:"))
        }
    }
    else {
        //TODO: Handle error
    }

    photoOverlay.backgroundColor = UIColor(white: 0, alpha: 0.5)
}

当他们按下按钮时,将调用此函数:

@IBAction func didPressTakePhoto(sender: UIButton) {
    if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) {
        videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
        stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
            if (sampleBuffer != nil) {
                var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                var dataProvider = CGDataProviderCreateWithCFData(imageData)
                var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)

                self.capturedImage = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)

                self.capturedPhoto.image = self.capturedImage
            }
        })
    }
}

此代码可让我以我想要的任何纵横比拍摄照片。有什么方法可以修改 didPressTakePhoto 代码来制作视频吗?

我什至找不到一个 swift 关于如何制作自定义录像机的教程。

您的 AVCaptureSession 目前只有一个输出,即 AVCaptureStillImageOutput。如果您想捕获视频,您需要添加 AVCaptureVideoDataOutputAVCaptureMovieFileOutput 作为捕获会话的输出。

这里是 AV Foundation 编程指南:Still and Video Media Capture