OSX 使用 AVScreenCaptureInput 截屏

OSX Screencapturing using AVScreenCaptureInput

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

AVCaptureSession 可以吗?

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

如果不是 AVFoundation class/framework,那么推荐哪个?

如果你想要一个连续的 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

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

input.minFrameDuration = CMTimeMake(1, 60);

对于更成熟的实现,其中更多的错误检查,请参阅 Apple 的 AVScreenShack sample code