-1

フロントカメラを使用してユーザーに「ミラー」を表示する「ミラー」のようなビューをアプリで作成しました。私が抱えている問題は、このコードに何週間も触れていないことです (そして、それは機能しました) が、今はもう一度テストしていますが、機能していません。コードは以前と同じで、エラーは発生せず、ストーリーボードのビューは以前とまったく同じです。何が起こっているのかわからないので、このウェブサイトが役立つことを願っていました.

これが私のコードです:

if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
        //If the front camera is available, show the camera


        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        AVCaptureOutput *output = [[AVCaptureStillImageOutput alloc] init];
        [session addOutput:output];

        //Setup camera input
        NSArray *possibleDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        //You could check for front or back camera here, but for simplicity just grab the first device
        AVCaptureDevice *device = [possibleDevices objectAtIndex:1];
        NSError *error = nil;
        // create an input and add it to the session
        AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; //Handle errors

        //set the session preset
        session.sessionPreset = AVCaptureSessionPresetHigh; //Or other preset supported by the input device
        [session addInput:input];

        AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
        //Now you can add this layer to a view of your view controller
        [cameraView.layer addSublayer:previewLayer];
        previewLayer.frame = self.cameraView.bounds;
        [session startRunning];
        if ([session isRunning]) {
            NSLog(@"The session is running");
        }
        if ([session isInterrupted]) {
            NSLog(@"The session has been interupted");
        }

    } else {
        //Tell the user they don't have a front facing camera
    }

よろしくお願いします。

4

1 に答える 1

5

これが問題かどうかはわかりませんが、コードとコメントの間に矛盾があります。矛盾は、次のコード行にあります。

AVCaptureDevice *device = [possibleDevices objectAtIndex:1];

上記のコメントでは、「...簡単にするために、最初のデバイスを取得するだけです」と書かれています。ただし、コードは 2 番目のデバイスを取得しており、NSArray0 からインデックスが付けられています。フロント カメラがアレイ内の 2 番目のデバイスになると想定していると思われるため、コメントを修正する必要があると思います。

最初のデバイスが背面カメラで、2 番目のデバイスが前面カメラであるという仮定に基づいて作業している場合、これは危険な仮定です。possibleDevicesフロントカメラであるデバイスのリストを確認する方が、はるかに安全で将来性があります.

次のコードは、リストを列挙し、フロント カメラを使用してpossibleDevices作成します。input

// Find the front camera and create an input and add it to the session
AVCaptureDeviceInput* input = nil;

for(AVCaptureDevice *device in possibleDevices) {
    if ([device position] == AVCaptureDevicePositionFront) {
        NSError *error = nil;

        input = [AVCaptureDeviceInput deviceInputWithDevice:device 
                                                      error:&error]; //Handle errors
        break;
    }
}

更新:問題のコードをそのまま切り取って単純なプロジェクトに貼り付けたところ、問題なく動作しています。フロントカメラの映像を見ています。問題については、おそらく他の場所を探す必要があります。cameraViewまず、および関連するレイヤーを確認したいと思います。

于 2012-09-17T05:50:24.913 に答える