gpt4 book ai didi

ios - 如何在 Swift 中使用 avfoundation 录制视频?

转载 作者:IT王子 更新时间:2023-10-29 05:11:20 26 4
gpt4 key购买 nike

我想弄清楚如何在 Swift 中使用 AVFoundation 录制视频。我已经创建了一个自定义相机,但我只知道如何用它拍摄静态照片,但我不知道如何录制视频。据我了解,您必须使用 AVCaptureVideoDataOutput 从录制中获取数据,但我不知道如何开始录制和实现委托(delegate)方法。

整个 AVFoundation 编程指南/静态和视频媒体捕获都在 Objective-C 中,我似乎无法破译它。这是我完成此任务的尝试:

首先我设置了相机/捕获 session

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()

最后是委托(delegate)方法

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

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

并没有像你想象的那样发生,因为我不知道如何正确地实现它。

最佳答案

我试过你的代码。当设置一个有意义的 filePath 时,一切都会好起来的。像这样更改您的 filePath,您将调用委托(delegate)方法:

    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)

关于ios - 如何在 Swift 中使用 avfoundation 录制视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33249041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com