您好,我跟隨由Jared Davidson創建自定義相機視圖並使用AVFoundation保存圖片的過程。 https://www.youtube.com/watch?v=w0O3ZGUS3pk保存視頻使用AVFoundation斯威夫特
但是我想記錄並保存視頻,而不是圖像。有人可以幫我嗎?我確定它的簡單但蘋果的文檔是用Objective-C編寫的,我無法破譯它。
這是我的代碼。謝謝。
import UIKit
import AVFoundation
class ViewController: UIViewController {
var captureSession = AVCaptureSession()
var sessionOutput = AVCaptureStillImageOutput()
var previewLayer = AVCaptureVideoPreviewLayer()
@IBOutlet var cameraView: UIView!
override func viewWillAppear(animated: Bool) {
let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
for device in devices {
if device.position == AVCaptureDevicePosition.Front{
do{
let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice)
if captureSession.canAddInput(input){
captureSession.addInput(input)
sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if captureSession.canAddOutput(sessionOutput){
captureSession.addOutput(sessionOutput)
captureSession.startRunning()
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer)
previewLayer.position = CGPoint(x: self.cameraView.frame.width/2, y: self.cameraView.frame.height/2)
previewLayer.bounds = cameraView.frame
}
}
}
catch{
print("Error")
}
}
}
}
@IBAction func TakePhoto(sender: AnyObject) {
if let videoConnection = sessionOutput.connectionWithMediaType(AVMediaTypeVideo){
sessionOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
buffer, error in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData)!, nil, nil, nil)
})
}
}
}
您可以從Xcode>設備> iPhone> _app name_>下載容器中的設備下載文檔目錄。您可以通過調用'didFinishRecordingToOutputFileAtURL'委託方法中的'UISaveVideoAtPathToSavedPhotosAlbum()'將視頻保存到相機膠捲。如果您的問題得到解答,請接受此答案。 –
哈哈非常感謝!希望這可以幫助別人,因爲我看到很多人在問。 –