AVCaptureDevice无法捕获相机

时间:2014-07-01 08:07:11

标签: ios avcapturedevice

我正在尝试使用AVCaptureDevice从我的iphone上使用后置摄像头。我尝试了AVCaptureDevicePositionBackAVCaptureDevicePositionFront,但无论如何它仍然使用FrontCamera。

这是我的代码:

- (void)setupCamera
{
    _captureDevice = nil;

    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

    for (AVCaptureDevice *device in devices)
    {
        if (device.position == AVCaptureDevicePositionBack)
        {
            _captureDevice = device;
            break;
        }
    }

}


- (void)turnCameraOn
{
    NSError *error;

    _session = [[AVCaptureSession alloc] init];
    [_session beginConfiguration];
    [_session setSessionPreset:AVCaptureSessionPresetMedium];

    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:_captureDevice error:&error];

    if (input == nil)
        NSLog(@"%@", error);

    [_session addInput:input];

    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
    [output setSampleBufferDelegate:self queue:dispatch_queue_create("myQueue", NULL)];
    output.videoSettings = @{(id)kCVPixelBufferPixelFormatTypeKey:@(kCVPixelFormatType_32BGRA)};
    output.alwaysDiscardsLateVideoFrames = YES;

    [_session addOutput:output];

    [_session commitConfiguration];
    [_session startRunning];
}


- (void)turnCameraOff
{
    [_session stopRunning];
    _session = nil;
}

1 个答案:

答案 0 :(得分:1)

使用以下代码:

    AVCaptureDevicePosition desiredPosition;

    if (isUsingFrontFacingCamera)

        desiredPosition = AVCaptureDevicePositionBack;

    else

        desiredPosition = AVCaptureDevicePositionFront;



    for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {

        if ([d position] == desiredPosition) {

            [[captureVideoPreviewLayer session] beginConfiguration];

            AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];

            for (AVCaptureInput *oldInput in [[captureVideoPreviewLayer session] inputs]) {

                [[captureVideoPreviewLayer session] removeInput:oldInput];

            }

            [[captureVideoPreviewLayer session] addInput:input];

            [[captureVideoPreviewLayer session] commitConfiguration];

            break;

        }

    }