我是iOS的新手,使用swift进行简单的应用,因为我需要一个自定义相机。我正在使用AVFoundation,但应用程序长时间显示黑屏,然后它正在加载相机。这是我的代码
func prepareCamera() {
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
if frontCam{
if let availableDevices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .front).devices {
captureDevice = availableDevices.first
DispatchQueue(label: "prepare").async {
self.beginSession()
}
}
}else{
if let availableDevices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .back).devices {
captureDevice = availableDevices.first
beginSession()
}
}
}
@IBAction func switchCameraBtnClicked(_ sender: Any) {
frontCam = !frontCam
prepareCamera()
}
func beginSession () {
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
captureSession.removeInput(input)
}
}
if captureSession.inputs.isEmpty {
captureSession.addInput(captureDeviceInput)
}
}catch {
print(error.localizedDescription)
}
if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
self.previewLayer = previewLayer
// self.view.layer.addSublayer(self.previewLayer)
self.view.layer.insertSublayer(self.previewLayer, at: 0)
self.previewLayer.frame = self.view.layer.frame
captureSession.startRunning()
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)]
dataOutput.alwaysDiscardsLateVideoFrames = true
if captureSession.canAddOutput(dataOutput) {
captureSession.addOutput(dataOutput)
}
captureSession.commitConfiguration()
let queue = DispatchQueue(label: "com.graymatics.customcamera")
dataOutput.setSampleBufferDelegate(self, queue: queue)
}
}
如果代码不正确,请纠正我。
答案 0 :(得分:0)
终于找到了解决方案
这是我的代码:
override func viewDidDisappear(_ animated: Bool) {
self.stopCaptureSession()
}
func stopCaptureSession () {
self.captureSession.stopRunning()
if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
self.captureSession.removeInput(input)
}
}
}
从当前视图控制器开始移动时,需要停止会话。