2015-06-14 4 views
3

Я следил за учебником, который проводил путь к созданию пользовательского, но простого приложения для камеры, почти точно к потребностям использования, которое мне бы это понравилось. На самом деле у меня есть две проблемы, которые мне нужно изменить, но сейчас я сосредоточусь на этом первом.Objective-C Передняя камера AVCaptureDevice

Следующий код позволяет использовать заднюю камеру, но мне в основном нужно ее изменить, чтобы я мог использовать переднюю камеру. Я также свяжусь с видео, которое я получил от него, чтобы дать им кредит, и я последовал за тем, что один из комментаторов сказал об использовании передней камеры, но ответ вообще не помог.

https://www.youtube.com/watch?v=Xv1FfqVy-KM

Я не отлично кодирования вообще, но при попытке узнать. Любая помощь будет оценена! Большое спасибо.

@interface ViewController() 

@end 

@implementation ViewController 

AVCaptureSession *session; 
AVCaptureStillImageOutput *StillImageOutput; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)viewWillAppear:(BOOL)animated { 

    session = [[AVCaptureSession alloc] init]; 

    [session setSessionPreset:AVCaptureSessionPresetPhoto]; 

    AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 

    NSError *error; 

    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error]; 



    if ([session canAddInput:deviceInput]) { 

     [session addInput:deviceInput]; 

    } 



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

    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill]; 

    CALayer *rootLayer = [[self view] layer]; 

    [rootLayer setMasksToBounds:YES]; 

    CGRect frame = frameforcapture.frame; 



    [previewLayer setFrame:frame]; 



    [rootLayer insertSublayer:previewLayer atIndex:0]; 





    StillImageOutput = [[AVCaptureStillImageOutput alloc] init]; 

    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil]; 

    [StillImageOutput setOutputSettings:outputSettings]; 



    [session addOutput:StillImageOutput]; 



    [session startRunning]; 

} 



- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)takephoto:(id)sender { 

    AVCaptureConnection *videoConnection = nil; 

    for (AVCaptureConnection *connection in StillImageOutput.connections) { 
     for (AVCaptureInputPort *port in [connection inputPorts ]) { 
      if ([[port mediaType] isEqual:AVMediaTypeVideo]) { 
       videoConnection = connection; 
       break; 
      } 
     } 
    } 
    [StillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) { 
     if (imageDataSampleBuffer != NULL) { 
      NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; 
      UIImage *image = [UIImage imageWithData:imageData]; 
      imageView.image = image; 
     } 
    }]; 
} 

@end 

ответ

4

Этот код возвращает экземпляр AVCaptureDevice для устройства по умолчанию данного типа носителя.

AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 

изменить этот код

.... 
AVCaptureDevice *inputDevice = nil; 
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; 
for(AVCaptureDevice *camera in devices) { 
    if([camera position] == AVCaptureDevicePositionFront) { // is front camera 
     inputDevice = camera; 
     break; 
    } 
} 
...... 
+0

Спасибо очень много, не может быть более совершенным! Я сделал то, что хотел. – Noodleme

0
- (IBAction)btnCameraClicked:(id)sender { 

    AVCaptureDevicePosition desiredPosition; 
    if (isUsingFrontFacingCamera) 
     desiredPosition = AVCaptureDevicePositionBack; 
    else 
     desiredPosition = AVCaptureDevicePositionFront; 

    for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { 
     if ([d position] == desiredPosition) { 
      [[previewLayer session] beginConfiguration]; 
      AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil]; 
      for (AVCaptureInput *oldInput in [[previewLayer session] inputs]) { 
       [[previewLayer session] removeInput:oldInput]; 
      } 
      [[previewLayer session] addInput:input]; 
      [[previewLayer session] commitConfiguration]; 
      break; 
     } 
    } 
    isUsingFrontFacingCamera = !isUsingFrontFacingCamera; 
} 

// Объявите в файле .h

AVCaptureVideoPreviewLayer *previewLayer; 
BOOL isUsingFrontFacingCamera; 
Смежные вопросы