cor*_*erg -1 camera objective-c uiimagepickercontroller avcapturesession
我在我的应用程序中创建了一个"镜像"视图,它使用前置摄像头向用户显示"镜像".我遇到的问题是我几周没有触及这个代码(当时它确实有效)但是现在我再次测试它并且它不起作用.代码与以前相同,没有错误出现,故事板中的视图与之前完全相同.我不知道发生了什么,所以我希望这个网站会有所帮助.
这是我的代码:
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
}
Run Code Online (Sandbox Code Playgroud)
先谢谢你.
不确定这是否是问题,但代码和注释之间存在不一致.不一致是使用以下代码行:
AVCaptureDevice *device = [possibleDevices objectAtIndex:1];
Run Code Online (Sandbox Code Playgroud)
在上面的评论中,它说:"为了简单起见,只需抓住第一台设备".然而,代码是抓住第二个设备,NSArray从0开始索引.我相信评论应该更正,因为我认为你假设前置摄像头将是阵列中的第二个设备.
如果你假设第一个设备是后置摄像头而第二个设备是前置摄像头,那么这是一个危险的假设.检查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;
}
}
Run Code Online (Sandbox Code Playgroud)
更新:我刚刚将问题中的代码剪切并粘贴到一个简单的项目中,它对我来说很好.我正在看前置摄像头的视频.您可能应该在其他地方查找该问题.首先,我倾向于检查cameraView和关联的图层.
| 归档时间: |
|
| 查看次数: |
457 次 |
| 最近记录: |