【问题标题】:AVCaptureStillImageOutput never calls completition handlerAVCaptureStillImageOutput 从不调用完成处理程序
【发布时间】:2012-09-08 20:26:03
【问题描述】:

以下代码不起作用。怎么了?

AVCaptureDevice * videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput * videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
AVCaptureSession * captureSession = [[AVCaptureSession alloc] init];
captureSession.sessionPreset = AVCaptureSessionPresetMedium;
if (![captureSession canAddInput:videoInput])
    NSLog(@"Can't add input");
[captureSession addInput:videoInput];

self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
[self.stillImageOutput setOutputSettings:@{AVVideoCodecKey:AVVideoCodecJPEG}];
if (![captureSession canAddOutput:videoInput])
    NSLog(@"Can't add output");
[captureSession addOutput:self.stillImageOutput];

[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:[self.stillImageOutput.connections lastObject]
                                                   completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
                                                   {
                                                       NSLog(@"!!!");

                                                       if (imageDataSampleBuffer == NULL)
                                                       {
                                                           NSLog(@"%@", error);
                                                           return;
                                                       }

                                                       NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                       UIImage *image = [[UIImage alloc] initWithData:imageData];
                                                       self.imageView.image = image;
                                                   }];

// Creating preview layer
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:captureSession];
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.previewLayer.frame = self.view.layer.bounds;
[self.view.layer addSublayer:self.previewLayer];

[captureSession startRunning];

AVCaptureVideoPreviewLayer 效果很好,但 AVCaptureStillImageOutput 根本不调用完成处理程序...

【问题讨论】:

    标签: ios camera avfoundation video-capture


    【解决方案1】:

    您需要以一种方法设置和启动会话, 然后有一个单独的捕获方法:

    /////////////////////////////////////////////////
    ////
    //// Utility to find front camera
    ////
    /////////////////////////////////////////////////
    -(AVCaptureDevice *) frontFacingCameraIfAvailable{
    
        NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        AVCaptureDevice *captureDevice = nil;
    
       for (AVCaptureDevice *device in videoDevices){
    
            if (device.position == AVCaptureDevicePositionFront){
    
                captureDevice = device;
                break;
            }
        }
    
        //  couldn't find one on the front, so just get the default video device.
        if (!captureDevice){
    
            captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        }
    
        return captureDevice;
    }
    
    /////////////////////////////////////////////////
    ////
    //// Setup Session, attach Video Preview Layer
    //// and Capture Device, start running session
    ////
    /////////////////////////////////////////////////
    -(void) setupCaptureSession {
        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        session.sessionPreset = AVCaptureSessionPresetMedium;
    
        AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer    alloc] initWithSession:session];
        [self.view.layer addSublayer:captureVideoPreviewLayer];
    
        NSError *error = nil;
        AVCaptureDevice *device = [self frontFacingCameraIfAvailable];
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
        if (!input) {
            // Handle the error appropriately.
            NSLog(@"ERROR: trying to open camera: %@", error);
        }
        [session addInput:input];
    
        self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
        NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
        [self.stillImageOutput setOutputSettings:outputSettings];
    
        [session addOutput:self.stillImageOutput];
    
        [session startRunning];
    }
    
    
    /////////////////////////////////////////////////
    ////
    //// Method to capture Still Image from 
    //// Video Preview Layer
    ////
    /////////////////////////////////////////////////
    -(void) captureNow {
        AVCaptureConnection *videoConnection = nil;
        for (AVCaptureConnection *connection in self.stillImageOutput.connections) {
            for (AVCaptureInputPort *port in [connection inputPorts]) {
                if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                    videoConnection = connection;
                    break;
                }
            }
            if (videoConnection) { break; }
        }
    
        NSLog(@"about to request a capture from: %@", self.stillImageOutput);
        __weak typeof(self) weakSelf = self;
        [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
    
             NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
             UIImage *image = [[UIImage alloc] initWithData:imageData];
    
             [weakSelf displayImage:image];
         }];
    }
    

    【讨论】:

    • “在单独的方法中执行”解决此问题的唯一原因是它具有将 AVCaptureSession 保留在控制器中的副作用。我认为 AVCaptureStillImageOutput 中存在一个错误,使其在自动引用计数模式下无法跟踪其 AVCaptureSession。
    • 啊,好点子。是的 - 我和一位同事试图让它像你上周五尝试的那样工作,但没有运气。我一直到凌晨,发现最好单独初始化 AVCaptureSession。祝你好运!
    • 我正在尝试在 swift 中做同样的事情,但它不起作用.....有没有它不起作用的原因..我有相同的代码....
    • 在我的情况下 stillImageOutput.connections 是 nil 因为我分配了 AVCaptureSession 和 AVCaptureVideoPreviewLayer 两次,所以只需添加检查 session == nil 然后只做 [[AVCaptureStillImageOutput alloc] init] 和所有 StillImageOutput 预设跨度>
    【解决方案2】:

    这很好用:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        AVCaptureDevice * videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        AVCaptureDeviceInput * videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
        AVCaptureSession * captureSession = [[AVCaptureSession alloc] init];
        captureSession.sessionPreset = AVCaptureSessionPresetMedium;
        [captureSession addInput:videoInput];
        [captureSession addOutput:self.stillImageOutput];
        [captureSession startRunning];
    
        // Creating preview layer
        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:captureSession];
        self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        self.previewLayer.frame = self.view.layer.bounds;
        [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    }
    
    - (void)timerFired:(NSTimer *)timer
    {
        [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:[self.stillImageOutput.connections lastObject]
                                                           completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
                                                           {
                                                               NSLog(@"!!!");
    
                                                               if (imageDataSampleBuffer == NULL)
                                                                   NSLog(@"%@", error);
    
                                                               NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                               UIImage * image = [[UIImage alloc] initWithData:imageData];
                                                               self.imageView.image = image;
                                                           }];
    }
    
    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
    
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      相关资源
      最近更新 更多