Search code examples
iosxcodeavcapturesession

Audio/video out of sync after switch camera


I'm try create application where I can record video from different cameras on device during recording. For example. User press button "start record" from front camera, after 5 second recording user press button "Switch Camera" and application change video source from front to back camera and recording continue. For camera swithcing I use next code:

NSError *error;
AVCaptureDeviceInput *newVideoInput;
AVCaptureDevicePosition currentCameraPosition = [[videoInput device] position];

if (currentCameraPosition == AVCaptureDevicePositionBack)
{
    currentCameraPosition = AVCaptureDevicePositionFront;
}
else
{
    currentCameraPosition = AVCaptureDevicePositionBack;
}

AVCaptureDevice *backFacingCamera = nil;
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) 
{
    if ([device position] == currentCameraPosition)
    {
        backFacingCamera = device;
    }
}
newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:backFacingCamera error:&error];

if (newVideoInput != nil)
{
    [_captureSession beginConfiguration];

    [_captureSession removeInput:videoInput];
    if ([_captureSession canAddInput:newVideoInput])
    {
        [_captureSession addInput:newVideoInput];
        videoInput = newVideoInput;
    }
    else
    {
        [_captureSession addInput:videoInput];
    }
    //captureSession.sessionPreset = oriPreset;
    [_captureSession commitConfiguration];
}

_inputCamera = backFacingCamera;

After this appication change video sourse and continue writing, but... audio/video out of sync... Can anybody hehp me with this problem?

Thank you.


Solution

  • you need to stop recording, switch and start it again. the camera switch isnt instant AFAIK

    cant you record into n files and later stich them together?

    try using individual AVMutableComposition tracks and then setting a mutablecomposition for audio and one for video. (see Merging two m4v Movie Files Using AVMutableComposition - Videos Will Not Merge)