使用AVScreenCaptureInput的OSX屏幕捕获

OSX Screencapturing using AVScreenCaptureInput

本文关键字:屏幕 OSX AVScreenCaptureInput 使用      更新时间:2023-10-16

在我的mac应用程序中,我需要抓取屏幕并将其发送到另一端,

AVCaptureSession有可能吗?

如果是,我只需要RGB或YUV数据,而不是音频,可以配置它吗?

如果不是AVFoundation类/框架,那么推荐哪一个?

如果你想要一个连续的yuv图像流,你可以这样做:

#import <AVFoundation/AVFoundation.h>
@interface ScreenCapture() <AVCaptureVideoDataOutputSampleBufferDelegate>
@property (nonatomic) AVCaptureSession *captureSession;
@end
@implementation ScreenCapture
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.captureSession = [[AVCaptureSession alloc] init];
        AVCaptureScreenInput *input = [[AVCaptureScreenInput alloc] initWithDisplayID:CGMainDisplayID()];
        [self.captureSession addInput:input];
        AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
        [self.captureSession addOutput:output];
        // TODO: create a dedicated queue.
        [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
        [self.captureSession startRunning];
    }
    return self;
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    // sampleBuffer contains screen cap, for me it's yuv
}
@end

这给了我大约每秒15帧的速度。您可以通过降低最低帧速率来获得更高的帧速率:

input.minFrameDuration = CMTimeMake(1, 60);

有关更成熟的实现,即更多的错误检查,请参阅Apple的AVScreenShack示例代码。