Xin chào Tôi đã theo một khóa học của Jared Davidson để tạo chế độ xem máy ảnh tùy chỉnh và lưu ảnh bằng AVFoundation. https://www.youtube.com/watch?v=w0O3ZGUS3pkLưu Video Sử dụng AVFoundation Swift
Tuy nhiên, tôi muốn ghi lại và lưu video thay vì hình ảnh. Ai đó có thể giúp tôi ở đây không? Tôi chắc chắn tài liệu đơn giản nhưng táo của nó được viết trong Objective-C và tôi không thể giải mã nó.
Đây là mã của tôi. Cảm ơn.
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)
})
}
}
}
Bạn có thể tải xuống thư mục Documents từ thiết bị trong Xcode> Thiết bị> iPhone> _app name_> Tải xuống vùng chứa. Bạn có thể lưu video vào thư viện ảnh bằng cách gọi 'UISaveVideoAtPathToSavedPhotosAlbum()' từ phương thức ủy nhiệm 'didFinishRecordingToOutputFileAtURL'. Nếu câu hỏi của bạn được trả lời, vui lòng chấp nhận câu trả lời này. –
Haha cảm ơn rất nhiều! Hy vọng rằng điều này sẽ giúp người khác cũng bởi vì tôi thấy rất nhiều người đã hỏi. –