Runt
2025-06-27 e21b1c797955a231f2bcf71818e0259fbb6aeba1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//
//  CameraCapture.swift
//  LiveProject
//
//  Created by 倪路朋 on 6/27/25.
//
import AVFoundation
 
class CameraCapture: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
    private let session = AVCaptureSession()
    var onFrame: ((CVPixelBuffer) -> Void)?
 
    func start() {
        guard let device = AVCaptureDevice.default(for: .video),
              let input = try? AVCaptureDeviceInput(device: device) else {
            print("❌ 相机设备无法创建")
            return
        }
 
        session.beginConfiguration()
        session.sessionPreset = .high
 
        if session.canAddInput(input) {
            session.addInput(input)
        }
 
        let output = AVCaptureVideoDataOutput()
        output.videoSettings = [
            kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA
        ]
        output.setSampleBufferDelegate(self, queue: DispatchQueue(label: "camera.queue"))
 
        if session.canAddOutput(output) {
            session.addOutput(output)
        }
 
        session.commitConfiguration()
        session.startRunning()
    }
 
    func captureOutput(_ output: AVCaptureOutput,
                       didOutput sampleBuffer: CMSampleBuffer,
                       from connection: AVCaptureConnection) {
        guard let buffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
        onFrame?(buffer)
    }
}