1

Я снимаю видео с помощью AVCaptureSession. Проблема в том, что я не понимаю всей логики ориентации видео. Я установил ориентацию видео, как это:AVCaptureSession видео ориентация iOS

AVCaptureConnection *captureConnection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo]; 
[captureConnection setVideoOrientation:AVCaptureVideoOrientationPortrait]; 

Так я записывать видео и показать предварительный просмотр пользователя, но видео ориентации всегда боком. И мне нужно, чтобы это всегда был портрет. Я нашел некоторые подобные проблемы на SO, но не смог найти решение.

Код, я использую для записи видео:

AVCaptureSession *session = [[AVCaptureSession alloc] init]; 
self.captureSession = session; 
AVCaptureDevice *VideoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 

if (VideoDevice) 
{ 
    NSError *error; 
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:VideoDevice error:&error]; 
    self.videoInputDevice = input; 
    if (!error) 
    { 
     if ([self.captureSession canAddInput:self.videoInputDevice]) 
      [self.captureSession addInput:self.videoInputDevice]; 
    } 
} 

AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; 
NSError *error = nil; 
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&error]; 
if (audioInput) 
    [self.captureSession addInput:audioInput]; 

[self.previewLayer removeFromSuperlayer]; 
self.previewLayer = nil; 

[self setPreviewLayer:[[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession]]; 
[self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill]; 

AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init]; 
self.movieFileOutput = movieFileOutput; 

Float64 TotalSeconds = kDefaultRecordingTime; 
int32_t preferredTimeScale = 30; 
CMTime maxDuration = CMTimeMakeWithSeconds(TotalSeconds, preferredTimeScale); 
self.movieFileOutput.maxRecordedDuration = maxDuration; 
self.movieFileOutput.movieFragmentInterval = kCMTimeInvalid; 
self.movieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024; 

if ([self.captureSession canAddOutput:self.movieFileOutput]) 
    [self.captureSession addOutput:self.movieFileOutput]; 

[self.captureSession setSessionPreset:AVCaptureSessionPresetMedium]; 

if ([self.captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720]) 
    [self.captureSession setSessionPreset:AVCaptureSessionPreset1280x720]; 

CGRect layerRect = [self.recordingView bounds]; 
[self.previewLayer setBounds:layerRect]; 
[self.previewLayer setPosition:CGPointMake(CGRectGetMidX(layerRect), 
              CGRectGetMidY(layerRect))]; 
[self.recordingView.layer addSublayer:self.previewLayer]; 

[self.recordingView bringSubviewToFront:self.recordButton]; 
[self.recordingView bringSubviewToFront:self.frontCameraButton]; 

AVCaptureConnection *captureConnection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo]; 
[captureConnection setVideoOrientation:AVCaptureVideoOrientationPortrait]; 


[self.captureSession commitConfiguration]; 
[self.captureSession startRunning]; 

я затем записать еще одно видео и смешать его с помощью AVMutableComposition. Но все мои видео поворачиваются горизонтально. Я не делаю никаких поворотов при смешивании с avmutablecomposition.

Я был бы очень признателен, если бы кто-то мог дать мне указания, что делать или, возможно, даже увидеть, что не так в коде, это было бы действительно оценено. Заранее спасибо!

+0

@Mayur Я проверил это и пробовал все от этого уже, не помогает. Кажется, что все, что я установил для моей записи, по-прежнему вращается по горизонтали. Я пытаюсь установить ориентацию при составлении дорожки с помощью AVMutableComposition. – Lukas

+0

Вы снимаете видео в портретном режиме? – Mayur

+0

@Mayur Да, я беру их в портретном режиме. Затем я использую AVMutableComposition для добавления музыки, действительно простых вещей без поворота или чего-то еще. Но мое видео горизонтально. Я сохраняю его на iphone и отправляю его на мой Mac, и он тоже на Mac. Поворот по горизонтали. Надевая голову на это уже три дня:/ – Lukas

ответ

1

Просто попробуйте это, чтобы решить вопрос ориентации:

Прежде всего удалить эти 2 строки из кода:

AVCaptureConnection *captureConnection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo]; 
[captureConnection setVideoOrientation:AVCaptureVideoOrientationPortrait]; 

Теперь в добавить этот код на том же месте:

AVCaptureConnection *videoConnection = nil; 

for (AVCaptureConnection *connection in [movieFileOutput connections]) 
{ 
    NSLog(@"%@", connection); 
    for (AVCaptureInputPort *port in [connection inputPorts]) 
    { 
     NSLog(@"%@", port); 
     if ([[port mediaType] isEqual:AVMediaTypeVideo]) 
     { 
      videoConnection = connection; 
     } 
    } 
} 

if([videoConnection isVideoOrientationSupported]) // **Here it is, its always false** 
{ 
    [videoConnection setVideoOrientation:[[UIDevice currentDevice] orientation]]; 
} 

Редакция:

  • Просто добавьте мой код в последний раз.

Я надеюсь, что это сработает.

+0

все равно:/ – Lukas

+0

@Lukas делает последнюю попытку и пытается добавить мой код в последний раз после этой строки [self.captureSession startRunning]; – Mayur

+0

все тот же:/ – Lukas

Смежные вопросы