2015-03-03 2 views
3

Я использую AV для записи видео через мое приложение, и у меня есть кнопка, которая меняет местами изображение камеры на переднюю и заднюю камеры, а задняя часть по умолчанию. Переключение с начала на передний план работает отлично. Тем не менее, при переключении с начала на задний план приложение вызывает сбои.AVCameraInput - сбой при переключении камеры спереди назад

- (IBAction)btnSwapCamerasClicked:(id)sender { 

//Change camera source 
if(session) 
{ 
    //Indicate that some changes will be made to the session 
    [session beginConfiguration]; 

    //Remove existing input 
    AVCaptureInput* currentCameraInput = [session.inputs objectAtIndex:0]; 
    [session removeInput:currentCameraInput]; 

    //Get new input 
    AVCaptureDevice *newCamera = nil; 
    if(((AVCaptureDeviceInput*)currentCameraInput).device.position == AVCaptureDevicePositionBack) 
    { 
     newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront]; 
    } 
    else 
    { 
     newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack]; 
    } 

    //Add input to session 
    NSError *err = nil; 
    AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err]; 
    if(!newVideoInput || err) 
    { 
     NSLog(@"Error creating capture device input: %@", err.localizedDescription); 
    } 
    else 
    { 
      //THIS IS THE SPOT THAT CRASHES. 
     [session addInput:newVideoInput]; 
    } 

    //Commit all the configuration changes at once 
    [session commitConfiguration]; 
} 

} 

Аварийная ситуация возникает в [session addInput: newVideoInput]; и я вернулся следующий текст ошибки:

2015-03-03 11: 25: 59.566 Сват App Beta [1769: 365194] * Нагрузочный приложение из-за неперехваченного исключением 'NSInvalidArgumentException', причина: «* Несколько аудио/видео AVCaptureInputs в настоящее время не поддерживаются. ' *** Первый стек бросить вызов: (0x185c002d4 0x1975c80e4 0x1843ad39c 0x1843accd4 0x10004ac14 0x18a818fb4 0x18a80201c 0x18a818950 0x18a8185dc 0x18a811a74 0x18a7e57f0 0x18aa85274 0x18a7e3d04 0x185bb8250 0x185bb74f4 0x185bb55a4 0x185ae1404 0x18f4eb6fc 0x18a84a2b4 0x10004bb70 0x197c6ea08) LibC++ abi.dylib: оканчивающиеся неперехваченного исключением типа NSException

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

Любые идеи?

+0

Update - Я думаю, что я нашел то, что может быть причиной проблемы. Инструкция My if для проверки положения камеры при попытке перейти от фронта к спине не работает. Я переписал if, чтобы добавить «else if cam is front» к else условному и третьему, а мой код передан третьему, который не проверяет никаких условий. – user2616830

+0

Обновление 2: Это привело меня к моему ответу. Ниже приведено решение, которое я использовал. – user2616830

ответ

2

Я решил свою проблему, переписав код для переключения камер на то, что я написал собственностью. Я создал NSString с именем currentCam, который меняю текст на «Назад» и «Фронт» в зависимости от текущей ситуации. Код ниже:

- (IBAction)btnSwapCamerasClicked:(id)sender { 

[session beginConfiguration]; 


if ([currentCam isEqualToString:@"Back"]) 
{ 
    NSArray *inputs = [session inputs]; 

    for (AVCaptureInput *input in inputs) 
    { 
     [session removeInput:input]; 
    } 

    //Video input 
    AVCaptureDevice *newCamera = nil; 
    newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront]; 

    //Audio input 
    AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; 
    AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil]; 


    NSError *err = nil; 
    AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err]; 
    if(!newVideoInput || err) 
    { 
     NSLog(@"Error creating capture device input: %@", err.localizedDescription); 
    } 
    else 
    { 

     [session addInput:newVideoInput]; 
     [session addInput:audioInput]; 

     newVideoInput = nil; 
     audioInput = nil; 
     audioDevice = nil; 
     newCamera = nil; 
     inputs = nil; 


    } 

    currentCam = @"Front"; 


} 
else if ([currentCam isEqualToString:@"Front"]) 
{ 
    NSArray *inputs = [session inputs]; 

    for (AVCaptureInput *input in inputs) 
    { 
     [session removeInput:input]; 
    } 

    //Video input 
    AVCaptureDevice *newCamera = nil; 
    newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack]; 

    //Audio input 
    AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; 
    AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil]; 


    NSError *err = nil; 
    AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err]; 
    if(!newVideoInput || err) 
    { 
     NSLog(@"Error creating capture device input: %@", err.localizedDescription); 
    } 
    else 
    { 

     [session addInput:newVideoInput]; 
     [session addInput:audioInput]; 

     newVideoInput = nil; 
     audioInput = nil; 
     audioDevice = nil; 
     newCamera = nil; 
     inputs = nil; 
    } 

    currentCam = @"Back"; 
} 
else 
{ 
    //Camera is some weird third camera that doesn't exist yet! :O 
    NSLog(@"wat"); 
} 

[session commitConfiguration]; 
} 
1

только это много коды может работать

- (IBAction)switchCamera:(id)sender { 

    [captureSession beginConfiguration]; 
    NSArray *inputs = [captureSession inputs]; 

    //Remove all inputs 
    for (AVCaptureInput *input in inputs) 
    { 
     [captureSession removeInput:input]; 
    } 

    //Video input 
    AVCaptureDevice *newCamera = nil; 
    if ([currentCam isEqualToString:@"Back"]){ 
     newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront]; 
      currentCam = @"Front"; 
    }else{ 
     newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack]; 
     currentCam = @"Back"; 
    } 
    //Audio input 
    AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; 
    AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil]; 
    NSError *err = nil; 

    AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err]; 
    if(!newVideoInput || err) 
    { 
     NSLog(@"Error creating capture device input: %@", err.localizedDescription); 
    } 
    else 
    { 
     [captureSession addInput:newVideoInput]; 
     [captureSession addInput:audioInput]; 
    } 
[captureSession commitConfiguration]; 
} 
Смежные вопросы