我正在尝试捕获系统的屏幕并处理数据。但是我在委托方法CMSampleBufferGetDataBuffer
中获得的样本缓冲区的值为零。captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection)
任何想法?下面是我的代码:
import Cocoa
import AVFoundation
class ViewController: NSViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
private lazy var sampleBufferDelegateQueue = DispatchQueue(label: "VideoCapture")
private lazy var captureSession: AVCaptureSession = {
let session = AVCaptureSession()
session.sessionPreset = .hd1280x720
if let input = AVCaptureScreenInput.init(displayID: CGMainDisplayID()) {
session.addInput(input)
}
let output = AVCaptureVideoDataOutput()
output.videoSettings = [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
kCVPixelBufferMetalCompatibilityKey as String: true
]
output.setSampleBufferDelegate(self, queue: self.sampleBufferDelegateQueue)
session.addOutput(output)
return session
}()
@IBAction func startAction(_ sender: Any) {
self.start()
}
override func viewDidLoad() {
super.viewDidLoad()
}
func start() {
guard !self.captureSession.isRunning else {
return
}
self.captureSession.startRunning()
}
func stop() {
guard self.captureSession.isRunning else {
return
}
self.captureSession.stopRunning()
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer);
print(blockBuffer ?? "nil")
}
}