Created
January 4, 2023 05:24
-
-
Save hassanvfx/4d6b038555c46a480a7342f99b4ed125 to your computer and use it in GitHub Desktop.
Basic Camera Display / Buffer Analysis in SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import AVFoundation | |
struct CameraView: View { | |
// Set up the AVCaptureSession and AVCaptureVideoPreviewLayer | |
let captureSession = AVCaptureSession() | |
let previewLayer = AVCaptureVideoPreviewLayer() | |
let cameraDelegate = CameraDelegate() | |
var body: some View { | |
// Use a GeometryReader to get the size of the view | |
GeometryReader { geometry in | |
// Set up the camera preview | |
ZStack { | |
PreviewLayerView(previewLayer: self.previewLayer) | |
.id("\(geometry.size.width)x\(geometry.size.height)") | |
} | |
.onAppear { | |
self.previewLayer.frame = geometry.frame(in: .global) | |
self.previewLayer.bounds = geometry.frame(in: .global) | |
self.previewLayer.session = captureSession | |
let videoOutput = AVCaptureVideoDataOutput() | |
videoOutput.setSampleBufferDelegate(self.cameraDelegate as AVCaptureVideoDataOutputSampleBufferDelegate, queue: DispatchQueue(label: "sample buffer delegate", attributes: [])) | |
guard let device = AVCaptureDevice.default(for: .video) else { | |
fatalError() | |
} | |
if let input = try? AVCaptureDeviceInput(device: device) { | |
captureSession.addInput(input) | |
} else { | |
print("camera input error") | |
} | |
if captureSession.canAddOutput(videoOutput) { | |
captureSession.addOutput(videoOutput) | |
} | |
self.captureSession.startRunning() | |
} | |
// Stop the capture session when the view disappears | |
.onDisappear { | |
self.captureSession.stopRunning() | |
} | |
} | |
} | |
} | |
struct PreviewLayerView: UIViewRepresentable { | |
let previewLayer: AVCaptureVideoPreviewLayer | |
func makeUIView(context: Context) -> UIView { | |
let view = UIView(frame: .zero) | |
view.layer.addSublayer(previewLayer) | |
return view | |
} | |
func updateUIView(_ uiView: UIView, context: Context) { | |
previewLayer.frame = uiView.bounds | |
} | |
} | |
class CameraDelegate: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate { | |
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { | |
// Analyze the frame here | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment