| | |
| | | |
| | | class CameraCapture: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate { |
| | | private let session = AVCaptureSession() |
| | | private var videoOutput: AVCaptureVideoDataOutput? |
| | | private var input: AVCaptureDeviceInput? |
| | | var onFrame: ((CVPixelBuffer) -> Void)? |
| | | |
| | | func start() { |
| | |
| | | return |
| | | } |
| | | |
| | | self.input = input |
| | | |
| | | session.beginConfiguration() |
| | | session.sessionPreset = .high |
| | | session.sessionPreset = .hd1920x1080 |
| | | |
| | | if session.canAddInput(input) { |
| | | session.addInput(input) |
| | |
| | | session.addOutput(output) |
| | | } |
| | | |
| | | self.videoOutput = output |
| | | |
| | | session.commitConfiguration() |
| | | session.startRunning() |
| | | print("📷 相机已开启") |
| | | } |
| | | |
| | | func captureOutput(_ output: AVCaptureOutput, |
| | | didOutput sampleBuffer: CMSampleBuffer, |
| | | from connection: AVCaptureConnection) { |
| | | guard let buffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } |
| | | let width = CVPixelBufferGetWidth(buffer) |
| | | let height = CVPixelBufferGetHeight(buffer) |
| | | //print("📷 当前帧尺寸: \(width)x\(height)") |
| | | onFrame?(buffer) |
| | | } |
| | | |
| | | func stop(){ |
| | | session.stopRunning() |
| | | session.beginConfiguration() |
| | | |
| | | if let input = input { |
| | | session.removeInput(input) |
| | | } |
| | | |
| | | if let output = videoOutput { |
| | | session.removeOutput(output) |
| | | } |
| | | |
| | | session.commitConfiguration() |
| | | |
| | | input = nil |
| | | videoOutput = nil |
| | | print("📷 相机已关闭") |
| | | } |
| | | } |