我正在尝试构建一个相机应用,我试图在我的主视图控制器中的viewDidLoad()中设置我的捕获会话。出于某种原因,每当我在手机上运行应用程序时,AVCaptureSession方法canAddOutput都会被评估为false:
var captureSession: AVCaptureSession!
var photoOutput: AVCapturePhotoOutput!
var previewLayer : AVCaptureVideoPreviewLayer!
//MARK: Outlets
@IBOutlet weak var previewView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
captureSession = AVCaptureSession()
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
//Ask permission to camera
let device = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .back)
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) in
if granted {
print("granted")
//Set up session
if let input = try? AVCaptureDeviceInput(device: device) {
print("Input = device")
if (self.captureSession.canAddInput(input)) {
self.captureSession.addInput(input)
print("Input added to capture session")
if (self.captureSession.canAddOutput(self.photoOutput)) {
print("Output added to capture session")
self.captureSession.addOutput(self.photoOutput)
self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
self.previewLayer.frame = self.previewView.bounds
self.previewView.layer.addSublayer(self.previewLayer!)
self.captureSession.startRunning()
print("Session is running")
}
}
}
}
else {
print("Goodbye")
}
})
}
不幸的是,我只能打印它直到"输入添加到捕获会话"。任何建议都会有所帮助 - 谢谢!
答案 0 :(得分:0)
您必须删除会话中添加的先前输出。您可以为此使用for循环。
for outputs in captureSession.outputs{ captureSession.removeOutput(outputs) }
然后尝试添加新的输出