Runt
2025-07-04 acf8e83cbf106b4350536d54eb46379dd86a623c
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//
//  CameraCapture.swift
//  LiveProject
//
//  Created by 倪路朋 on 6/27/25.
//
import AVFoundation
 
class CameraCapture: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
    private let session = AVCaptureSession()
    private var videoOutput: AVCaptureVideoDataOutput?
    private var input: AVCaptureDeviceInput?
    var onFrame: ((CVPixelBuffer) -> Void)?
 
    func start() {
        guard let device = AVCaptureDevice.default(for: .video),
              let input = try? AVCaptureDeviceInput(device: device) else {
            print("❌ 相机设备无法创建")
            return
        }
 
        self.input = input
 
        session.beginConfiguration()
        session.sessionPreset = .hd1920x1080
 
        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)
        }
 
        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("📷 相机已关闭")
    }
}