在我的应用程序中,我显示一个AVCaptureVideoPreviewLayer,然后当用户使用captureStillImageAsynchronouslyFromConnection函数在AVCaptureOutput.中单击一个按钮时,捕获一个静止图像。这对我来说一直很好,直到iPhone 5还没有完成。
我的设置代码是:
...
self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[self.imageOutput setOutputSettings:outputSettings];
self.captureSession = [[[AVCaptureSession alloc] init] autorelease];
[self.captureSession addInput:self.rearFacingDeviceInput];
[self.captureSession addOutput:self.imageOutput];
[self.captureSession setSessionPreset:AVCaptureSessionPresetPhoto];
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
self.previewLayer.frame = CGRectMake(0, 0, 320, 427);
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.captureSession startRunning];
[outputSettings release];我的捕获方法是:
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in self.imageOutput.connections){
for (AVCaptureInputPort *port in [connection inputPorts]){
if ([[port mediaType] isEqual:AVMediaTypeVideo] ){
videoConnection = connection;
break;
}
}
if (videoConnection) { break; }
}
//code to abort if not return 'soon'
...
[self.imageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error){
//use image here
}];captureStillImageAsynchronouslyFromConnection从未为我使用iPhone5完成
我已经测试过:
另外:
发布于 2014-05-06 08:37:20
好吧,这个代码很好用。测试了iPhone 4和5 (baseSDK 7.1,在ARC下)。
很少有你需要考虑的事情。
1)一定要正确设置rearFacingDeviceInput,
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[self setRearFacingDeviceInput:[AVCaptureDeviceInput deviceInputWithDevice:device error:nil]];2)正如Vincent所提到的,会有一个错误,尝试同时记录一个错误和一个imageSampleBuffer
3)会话的-startRunning和-stopRunning操作需要很长时间(秒,甚至5-6s),这些方法在完成所有工作之前不会返回,为了避免阻塞的UI,您不应该在主线程上调用这些方法,一种方法是使用GCD
dispatch_queue_t serialQueue = dispatch_queue_create("queue", NULL);
dispatch_async(serialQueue, ^{
[self.captureSession startRunning];
});如果仍然没有完成captureStillImageAsynchronously (为了确保这一点,在块中添加断点,并记录所有内容),您应该检查设备的照相机。我相信您的代码可以在所有iPhone 5设备上工作。希望这能帮上忙祝你好运。
https://stackoverflow.com/questions/12590330
复制相似问题