ios - 在 iOS 上使用 AVCaptureSession 加载摄像头速度很慢 - 如何加快速度?

标签 ios camera photo avcapturesession

现在我正在尝试允许用户在不使用 UIImagePickerController 的情况下在我的应用程序中拍照。我正在使用 AVCaptureSession 和所有相关类在我的一个 View Controller 上的全屏 View 上加载相机源作为子层。该代码有效,但不幸的是相机加载速度非常慢。通常需要 2-3 秒。这是我的代码:

session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;

if ([session canSetSessionPreset:AVCaptureSessionPresetHigh])
    //Check size based configs are supported before setting them
    [session setSessionPreset:AVCaptureSessionPresetHigh];

[session setSessionPreset:AVCaptureSessionPreset1280x720];

CALayer *viewLayer = self.liveCameraFeed.layer;
//NSLog(@"viewLayer = %@", viewLayer);

AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

captureVideoPreviewLayer.frame = viewLayer.bounds;
[viewLayer addSublayer:captureVideoPreviewLayer];

AVCaptureDevice *device;

if(isFront)
{
    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
else
{
    device = [self frontCamera];
}

AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
[session addInput:audioInput];

NSError *error = nil;
input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
    // Handle the error appropriately.
    //NSLog(@"ERROR: trying to open camera: %@", error);
}

[session addInput:input];
[session startRunning];

stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[stillImageOutput setOutputSettings:outputSettings];
[session addOutput:stillImageOutput];

有什么办法可以加快速度吗?我已经尝试使用 Grand Central Dispatch 和 NSThread 在另一个线程上加载它,虽然这阻止了应用程序卡住,但它使相机的加载时间更长。感谢您的帮助。

最佳答案

在我的例子中,我需要等待 session 开始运行

dispatch_async(queue) {
  self.session.startRunning()

  dispatch_async(dispatch_get_main_queue()) {
    self.delegate?.cameraManDidStart(self)

    let layer = AVCaptureVideoPreviewLayer(session: self.session)
  }
}

关于ios - 在 iOS 上使用 AVCaptureSession 加载摄像头速度很慢 - 如何加快速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21949080/

相关文章:

ios - Facebook SDK 4.4.0 logInWithReadPermissions无法在iOS 9的iPhone上使用

ios - 来自一个 View Controller 的输入附件 View 错误地出现在另一个 View Controller 中

Android 从 Webview 打开相机在 android 6+ 中不起作用

Android如何访问jpg中的位置数据

ios - 加粗 nsstring

iOS 11 密码自动填充不会将密码保存到钥匙串(keychain)

java - Android Auto Exposure Lock 空指针异常

android - HUAWEI P9 双摄像头 API (CAMERA API 2) - 捕捉黑白视频

swift - 如何导入一张图像并将其设置为 UIIMageView。然后再用另一个UIIMageView?

java - 如何在Android操作系统的手机上检索相机拍摄的照片?