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

时间:2015-05-15 04:09:16

标签: ios swift avfoundation

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

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代码制作视频?

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

1 个答案:

答案 0 :(得分:0)

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

AV基础编程指南:Still and Video Media Capture