我有一个应用程序,可以在AVCaptureVideoPreviewLayer上显示相机预览。 当应用程序进入后台会话时停止。问题是,当我再次打开应用程序时,然后在初始化新会话之前,从我在图层上停止会话的时间开始预览。如何在AVCaptureVideoPreviewLayer上清除此预览?我希望它只包含黑色背景,直到新会话开始工作。
代码的某些部分是下面的,但不是全部:
private var displayVideo = false {
didSet {
guard displayVideo != oldValue else { return }
if displayVideo {
// Configure video capture session.
captureSession = {
guard let captureDevice = self.captureDevice else { return nil }
let captureSession = AVCaptureSession()
captureSession.sessionPreset = AVCaptureSessionPresetHigh
let videoDeviceInput = try! AVCaptureDeviceInput(device: captureDevice)
guard captureSession.canAddInput(videoDeviceInput) else {
print("Warning. Failed to add input to capture session.")
return nil
}
captureSession.addInput(videoDeviceInput)
configureVideoDevice()
return captureSession
}()
configureVideoOrientation()
}
else { captureSession = nil }
}
}
private var captureSession: AVCaptureSession? {
didSet {
if oldValue != captureSession { oldValue?.stopRunning() }
cameraPreviewLayer.session = captureSession
captureSession?.startRunning()
}
}
private lazy var captureDevice: AVCaptureDevice? = {
guard let videoDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else {
print("Warning. Failed to get capture device.")
return nil
}
return videoDevice
}()
private lazy var cameraPreviewLayer: AVCaptureVideoPreviewLayer = {
let layer = self.layer as! AVCaptureVideoPreviewLayer
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
return layer
}()