AVCaptureVideoPreviewLayer没有显示

时间:2015-04-05 13:36:28

标签: objective-c macos avfoundation

目标是简单地显示网络摄像头的实时视频输入。

该代码是从Apple的一个示例中提炼出来的,并且它似乎至少部分有效,因为相机旁边的指示灯在运行时亮起。

我从故事板中的视图拖动到界面中的outlet属性,它现在连接为引用插座但没有显示任何内容,甚至没有设置黑色背景颜色。

知道我哪里出错了吗?

感谢您的帮助

编辑: 实际上,如果我在[previewViewLayer addSublayer:self.previewLayer];行设置断点并继续在调试器中运行,它的工作正常。必须有某种时间问题。

接口:

@property (retain) AVCaptureDevice *videoDevice;
@property (retain) AVCaptureDeviceInput *videoDeviceInput;
@property (retain) AVCaptureSession *session;
@property (retain) AVCaptureVideoPreviewLayer *previewLayer;

@property (assign) IBOutlet NSView *previewView;

实现:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getDevice];
    [self initSession];
}

- (void)initSession {
    // Create a capture session
//    self.session = [[AVCaptureSession alloc] init];
    [self setSession:[[AVCaptureSession alloc] init]];

    // Attach preview to session
    CALayer *previewViewLayer = [self.previewView layer];
    [previewViewLayer setBackgroundColor:CGColorGetConstantColor(kCGColorBlack)];
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [self.previewLayer setFrame:[previewViewLayer bounds]];
    [self.previewLayer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
    [previewViewLayer addSublayer:self.previewLayer];

    // Start the session
    [self.session startRunning];

    // Create a device input for the device and add it to the session
    NSError *error = nil;
    AVCaptureDeviceInput *newVideoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.videoDevice error:&error];

    [self.session addInput:newVideoDeviceInput];
    self.videoDeviceInput = newVideoDeviceInput;

    [self.session commitConfiguration];
}

- (void)getDevice {
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

    for (AVCaptureDevice *device in devices) {

        NSLog(@"Device name: %@", [device localizedName]);        
        self.videoDevice = device;
    }
}

1 个答案:

答案 0 :(得分:0)

解决了:

我已将[self initSession];- (void)viewDidLoad移至- (void)viewDidLayout

更新: 我稍后使用- (void)viewDidLayout遇到了更多问题,所以最终我转到- (void)viewDidAppear