UIlabel未在AVCaptureSession Delegate中更新

时间:2011-05-22 17:09:42

标签: iphone objective-c uilabel avfoundation avcapturesession

我正在学习目标c并做一个示例应用程序来从iPhone摄像头获取视频。我能够从相机获取信息并将其显示在屏幕上。此外,我试图在委托方法内的视频中为每个帧更新屏幕中的一些UILabel。但标签值并未始终更新。这是我正在使用的代码

此部分将初始化捕获

   - (void)initCapture 
{
     NSError *error = nil;
    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus] && [device lockForConfiguration:&error]) {
        [device setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
        [device unlockForConfiguration];
    }

    AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

     //AVCaptureStillImageOutput *imageCaptureOutput = [[AVCaptureStillImageOutput alloc] init];

     AVCaptureVideoDataOutput *captureOutput =[[AVCaptureVideoDataOutput alloc] init];

     captureOutput.alwaysDiscardsLateVideoFrames = YES;
     //captureOutput.minFrameDuration = CMTimeMake(1, 1);

     captureOutput.alwaysDiscardsLateVideoFrames = YES; 
     dispatch_queue_t queue;
     queue = dispatch_queue_create("cameraQueue", NULL);
     [captureOutput setSampleBufferDelegate:self queue:queue];
     dispatch_release(queue);
     // Set the video output to store frame in BGRA (It is supposed to be faster)
     NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; 
     NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA]; 
     NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key]; 
     [captureOutput setVideoSettings:videoSettings]; 

     self.captureSession = [[AVCaptureSession alloc] init];

     [self.captureSession addInput:captureInput];
     [self.captureSession addOutput:captureOutput];


     self.prevLayer = [AVCaptureVideoPreviewLayer layerWithSession: self.captureSession];
     self.prevLayer.frame = CGRectMake(0, 0, 320, 320);
     self.prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;



     [self.videoPreview.layer addSublayer: self.prevLayer];     

     [self.captureSession startRunning]; 


     }

为每个视频帧调用此方法。

#pragma mark AVCaptureSession delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput 
     didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer 
     fromConnection:(AVCaptureConnection *)connection 
    { 

        i++;
        self.lblStatus.Text = [NSString stringWithFormat:@"%d",i];
    }

我正在尝试在此方法中打印UILabel,但它不会始终打印。标签文本的更改有很多延迟。

有人可以帮忙吗? 感谢。

1 个答案:

答案 0 :(得分:3)

您的sampleBufferDelegate的captureOutput是从非主线程调用的 - 从那里更新GUI对象没有任何好处。请尝试使用performSelectorOnMainThread。