最近又在弄短视频录制,解决一个问题又来一个问题。还好百度跟谷歌都是那么滴强大,基本上都能解决我遇到的问题。不过别人的答案不一定就是完全正确的答案,可能在自己的工程中就不起作用,所以还是需要我们自己去调试,发现问题,然后解决。
视频录制,我们需要根据设备方向来确定输出视频方向。比如横屏录制,如果不调整,那录出来的方向就不对。查看类属性,发现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];