Подтвердить что ты не робот

Как записать видео с avfoundation в Swift?

Я пытаюсь выяснить, как записать видео с помощью AVFoundation в Swift. Я добрался до создания пользовательской камеры, но я только понял, как сфотографироваться с ней, и я не могу понять, как записывать видео. Насколько я понимаю, вы должны использовать AVCaptureVideoDataOutput для получения данных из записи, но я не могу понять, как начать запись и реализовать методы делегата.

Вся программа AVFoundation Programing Guide/Still и Video Media Capture находится в Objective-C, и я не могу ее расшифровать. Здесь моя попытка выполнить эту задачу:

Сначала я установил сеанс камеры/захвата

override func viewDidLoad() {
    super.viewDidLoad()

    captureSession.sessionPreset = AVCaptureSessionPresetHigh
    let devices = AVCaptureDevice.devices()
    for device in devices {
        if (device.hasMediaType(AVMediaTypeVideo)) {
            if(device.position == AVCaptureDevicePosition.Back) {
                captureDevice = device as? AVCaptureDevice
                if captureDevice != nil {
                    beginSession()
                }
            }
        }
    }

}

Затем, как только beginSession() называется, я установил живой канал

func beginSession() {
    var err : NSError? = nil
    captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
    if err != nil {
        println("error: \(err?.localizedDescription)")
    }
    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    self.cameraView.layer.addSublayer(previewLayer)
    self.cameraView.bringSubviewToFront(takePhotoButton)
    self.cameraView.bringSubviewToFront(self.snappedPicture)
    self.cameraView.bringSubviewToFront(self.backButton)
    previewLayer?.frame = self.cameraView.layer.frame
    captureSession.startRunning()
}

Здесь, где я застреваю, когда пользователь нажимает на запись, чтобы фактически записать и захватить видео:

@IBAction func takeVideoAction(sender: AnyObject) {

    var recordingDelegate:AVCaptureFileOutputRecordingDelegate? = self

    var videoFileOutput = AVCaptureMovieFileOutput()
    self.captureSession.addOutput(videoFileOutput)

    let filePath = NSURL(fileURLWithPath: "filePath")

    videoFileOutput.startRecordingToOutputFileURL(filePath, recordingDelegate: recordingDelegate)

}

Затем я вызываю self.videoFileOutput.stopRecording().

Затем, наконец, методы делегата

func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
    return
}

func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
    return
}

И ничего не происходит, как вы можете себе представить, потому что я не могу понять, как правильно его реализовать.

4b9b3361

Ответ 1

Я пробовал свой код. Когда установлен значащий filePath, все идет хорошо. Измените свой filePath следующим образом, и вы получите методы делегата:

    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let filePath = documentsURL.URLByAppendingPathComponent("temp")

    // Do recording and save the output to the `filePath`
    videoFileOutput.startRecordingToOutputFileURL(filePath, recordingDelegate: recordingDelegate)