AVCaptureMovieFileOutput 视频方向(锁定竖屏or不锁定都可以)

本文介绍了在iOS设备上进行视频录制时如何根据设备方向正确设置输出视频的方向。提供了多种方法来获取设备方向,并讨论了使用CoreMotion进行更精确方向检测的技术细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近又在弄短视频录制,解决一个问题又来一个问题。还好百度跟谷歌都是那么滴强大,基本上都能解决我遇到的问题。不过别人的答案不一定就是完全正确的答案,可能在自己的工程中就不起作用,所以还是需要我们自己去调试,发现问题,然后解决。
视频录制,我们需要根据设备方向来确定输出视频方向。比如横屏录制,如果不调整,那录出来的方向就不对。查看类属性,发现videoOrientation,给它赋予正确的方向值就可以。这个值怎么获取呢?
方法一:[[UIApplication sharedApplication]statusBarOrientation]
方法二:[[UIDevice currentDevice]orientation];

   //监听设备
[[UIDevice currentDevice]beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(orientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
[[UIDevice currentDevice]endGeneratingDeviceOrientationNotifications];//在合适的地方加上这行代码

上面方法在不锁定竖屏方向都是有效的,一旦锁屏,监听就不起作用。那该怎么办呢?别急,我们还有一个最合适的好方法。那就是CoreMotion,先#import <CoreMotion/CoreMotion.h>,然后 CMMotionManager *motionManager;(设为私有变量或者属性,只是临时初始化得到一个实例时不起作用的)。

 motionManager = [[CMMotionManager alloc]init];
    motionManager.accelerometerUpdateInterval = .2;
    motionManager.gyroUpdateInterval = .2;
    [motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
        if(!error){
            [self outputData:accelerometerData.acceleration];
        }
        else{
            NSLog(@"%@",error);
        }
    }];
-(void)outputData:(CMAcceleration)data{
    UIInterfaceOrientation orientation;
    if(data.x >= 0.75){
        orientation = UIInterfaceOrientationLandscapeLeft;
    }
    else if (data.x<= -0.75){
        orientation = UIInterfaceOrientationLandscapeRight;
    }
    else if (data.y <= -0.75){
        orientation = UIInterfaceOrientationPortrait;
    }
    else if (data.y >= 0.75){
        orientation = UIInterfaceOrientationPortraitUpsideDown;
    }
    else{
        return;
    }
    orientationLast = orientation;
   
}

最后,在你点击按钮开始录制的地方添加下面几行代码:

   AVCaptureConnection *captureConnection = [self.fileOut connectionWithMediaType:AVMediaTypeVideo];
      captureConnection.videoOrientation = [self.captureVideoPreviewLayer connection].videoOrientation;

  [self.fileOut startRecordingToOutputFileURL:url recordingDelegate:self];

转载于:https://my.oschina.net/NycoWang/blog/1552814

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值