SLAvCaptureTool-bug副本.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. //
  2. // SLAvCaptureTool.m
  3. // DarkMode
  4. //
  5. // Created by wsl on 2019/9/20.
  6. // Copyright © 2019 wsl. All rights reserved.
  7. //
  8. #import "SLAvCaptureTool.h"
  9. #import <CoreMotion/CoreMotion.h>
  10. #define SL_kScreenWidth [UIScreen mainScreen].bounds.size.width
  11. #define SL_kScreenHeight [UIScreen mainScreen].bounds.size.height
  12. @interface SLAvCaptureTool () <AVCapturePhotoCaptureDelegate, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate>
  13. @property (nonatomic, strong) AVCaptureSession *session;
  14. @property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;//摄像头采集内容展示区域
  15. @property (nonatomic, strong) AVCaptureDeviceInput *audioInput; //音频输入流
  16. @property (nonatomic, strong) AVCaptureDeviceInput *videoInput; //视频输入流
  17. @property (nonatomic, strong) AVCapturePhotoOutput *capturePhotoOutput; //照片输出流
  18. @property (nonatomic, strong) AVCaptureVideoDataOutput *videoDataOutput; //视频数据帧输出流
  19. @property (nonatomic, strong) AVCaptureAudioDataOutput *audioDataOutput; //音频数据帧输出流
  20. @property (nonatomic, strong) AVAssetWriter *assetWriter; //音视频数据流文件写入
  21. @property (nonatomic, strong) AVAssetWriterInput *assetWriterVideoInput; //写入视频文件
  22. @property (nonatomic, strong) AVAssetWriterInput *assetWriterAudioInput; //写入音频文件
  23. @property (nonatomic, strong) NSDictionary *videoCompressionSettings;
  24. @property (nonatomic, strong) NSDictionary *audioCompressionSettings;
  25. @property (nonatomic, assign) BOOL canWrite; //是否能写入
  26. @property (nonatomic, copy) NSURL *outputFileURL; //音视频文件输出路径
  27. @property (nonatomic, assign) BOOL isRecording; //是否正在录制
  28. @property (nonatomic, assign) UIDeviceOrientation shootingOrientation; //拍摄时的手机方向
  29. @property (nonatomic, strong) CMMotionManager *motionManager; //运动传感器 监测设备方向
  30. @end
  31. @implementation SLAvCaptureTool
  32. //@synthesize videoInput = _videoInput;
  33. + (instancetype)sharedAvCaptureTool {
  34. static SLAvCaptureTool *avCaptureTool = nil;
  35. static dispatch_once_t onceToken;
  36. dispatch_once(&onceToken, ^{
  37. avCaptureTool = [[SLAvCaptureTool alloc] init];
  38. });
  39. return avCaptureTool;
  40. }
  41. #pragma mark - OverWrite
  42. - (instancetype)init {
  43. self = [super init];
  44. if (self) {
  45. }
  46. return self;
  47. }
  48. - (void)dealloc {
  49. [self stopRunning];
  50. }
  51. #pragma mark - HelpMethods
  52. //获取指定位置的摄像头
  53. - (AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition)positon{
  54. if (@available(iOS 10.2, *)) {
  55. AVCaptureDeviceDiscoverySession *dissession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInDualCamera,AVCaptureDeviceTypeBuiltInTelephotoCamera,AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:positon];
  56. for (AVCaptureDevice *device in dissession.devices) {
  57. if ([device position] == positon) {
  58. return device;
  59. }
  60. }
  61. } else {
  62. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  63. for (AVCaptureDevice *device in devices) {
  64. if ([device position] == positon) {
  65. return device;
  66. }
  67. }
  68. }
  69. return nil;
  70. }
  71. //最小缩放值 焦距
  72. - (CGFloat)minZoomFactor {
  73. CGFloat minZoomFactor = 1.0;
  74. if (@available(iOS 11.0, *)) {
  75. minZoomFactor = [self.videoInput device].minAvailableVideoZoomFactor;
  76. }
  77. return minZoomFactor;
  78. }
  79. //最大缩放值 焦距
  80. - (CGFloat)maxZoomFactor {
  81. CGFloat maxZoomFactor = [self.videoInput device].activeFormat.videoMaxZoomFactor;
  82. if (@available(iOS 11.0, *)) {
  83. maxZoomFactor = [self.videoInput device].maxAvailableVideoZoomFactor;
  84. }
  85. if (maxZoomFactor > 6) {
  86. maxZoomFactor = 6.0;
  87. }
  88. return maxZoomFactor;
  89. }
  90. #pragma mark - Getter
  91. - (AVCaptureSession *)session{
  92. if (_session == nil){
  93. _session = [[AVCaptureSession alloc] init];
  94. //高质量采集率
  95. [_session setSessionPreset:AVCaptureSessionPresetHigh];
  96. [_session addInput:self.videoInput]; //添加视频输入流
  97. [_session addInput:self.audioInput]; //添加音频输入流
  98. [_session addOutput:self.capturePhotoOutput]; //添加照片输出流
  99. [_session addOutput:self.videoDataOutput]; //视频数据输出流 纯画面
  100. [_session addOutput:self.audioDataOutput]; //音频数据输出流
  101. }
  102. return _session;
  103. }
  104. - (AVCaptureDeviceInput *)videoInput {
  105. if (_videoInput == nil) {
  106. //添加一个视频输入设备 默认是后置摄像头
  107. AVCaptureDevice *videoCaptureDevice = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];
  108. //创建视频输入流
  109. _videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoCaptureDevice error:nil];
  110. if (!_videoInput){
  111. NSLog(@"获得摄像头失败");
  112. return nil;
  113. }
  114. }
  115. return _videoInput;
  116. }
  117. - (AVCaptureDeviceInput *)audioInput {
  118. if (_audioInput == nil) {
  119. NSError * error = nil;
  120. //添加一个音频输入/捕获设备
  121. AVCaptureDevice * audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  122. _audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioCaptureDevice error:&error];
  123. if (error) {
  124. NSLog(@"获得音频输入设备失败:%@",error.localizedDescription);
  125. }
  126. }
  127. return _audioInput;
  128. }
  129. - (AVCapturePhotoOutput *)capturePhotoOutput {
  130. if (_capturePhotoOutput == nil) {
  131. _capturePhotoOutput = [[AVCapturePhotoOutput alloc] init];
  132. // _capturePhotoOutput.livePhotoCaptureEnabled = NO; //是否拍摄 live Photo
  133. }
  134. return _capturePhotoOutput;
  135. }
  136. - (AVCaptureVideoDataOutput *)videoDataOutput {
  137. if (_videoDataOutput == nil) {
  138. _videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
  139. dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
  140. [_videoDataOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(0, 0)];
  141. }
  142. return _videoDataOutput;
  143. }
  144. - (AVCaptureAudioDataOutput *)audioDataOutput {
  145. if (_audioDataOutput == nil) {
  146. _audioDataOutput = [[AVCaptureAudioDataOutput alloc] init];
  147. [_audioDataOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(0, 0)];
  148. }
  149. return _audioDataOutput;
  150. }
  151. - (AVCaptureVideoPreviewLayer *)previewLayer {
  152. if (_previewLayer == nil) {
  153. _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
  154. _previewLayer.videoGravity = AVLayerVideoGravityResizeAspect;
  155. }
  156. return _previewLayer;
  157. }
  158. - (AVAssetWriterInput *)assetWriterAudioInput {
  159. if (_assetWriterAudioInput == nil) {
  160. // 音频设置
  161. _audioCompressionSettings = @{ AVEncoderBitRatePerChannelKey : @(28000),
  162. AVFormatIDKey : @(kAudioFormatMPEG4AAC),
  163. AVNumberOfChannelsKey : @(1),
  164. AVSampleRateKey : @(22050) };
  165. _assetWriterAudioInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:self.audioCompressionSettings];
  166. _assetWriterAudioInput.expectsMediaDataInRealTime = YES;
  167. }
  168. return _assetWriterAudioInput;
  169. }
  170. - (CMMotionManager *)motionManager {
  171. if (!_motionManager) {
  172. _motionManager = [[CMMotionManager alloc] init];
  173. }
  174. return _motionManager;
  175. }
  176. - (BOOL)isRunning {
  177. return self.session.isRunning;
  178. }
  179. - (AVCaptureDevicePosition)devicePosition {
  180. if([[self.videoInput device] position] == AVCaptureDevicePositionUnspecified) {
  181. return AVCaptureDevicePositionBack;
  182. }
  183. return [[self.videoInput device] position];
  184. }
  185. - (CGFloat)videoZoomFactor {
  186. return [self.videoInput device].videoZoomFactor;
  187. }
  188. #pragma mark - Setter
  189. - (void)setOutputFileURL:(NSURL *)outputFileURL {
  190. _outputFileURL = outputFileURL;
  191. if (_assetWriter == nil) {
  192. _assetWriter = [AVAssetWriter assetWriterWithURL:outputFileURL fileType:AVFileTypeMPEG4 error:nil];
  193. }
  194. }
  195. - (void)setPreview:(nullable UIView *)preview {
  196. if (preview == nil) {
  197. [self.previewLayer removeFromSuperlayer];
  198. }else {
  199. self.previewLayer.frame = preview.bounds;
  200. // [preview.layer insertSublayer:self.previewLayer atIndex:0];
  201. [preview.layer addSublayer:self.previewLayer];
  202. }
  203. _preview = preview;
  204. }
  205. - (void)setVideoZoomFactor:(CGFloat)videoZoomFactor {
  206. NSError *error = nil;
  207. if (videoZoomFactor <= self.maxZoomFactor &&
  208. videoZoomFactor >= self.minZoomFactor){
  209. if ([[self.videoInput device] lockForConfiguration:&error] ) {
  210. [self.videoInput device].videoZoomFactor = videoZoomFactor;
  211. [[self.videoInput device] unlockForConfiguration];
  212. } else {
  213. NSLog( @"调节焦距失败: %@", error );
  214. }
  215. }
  216. }
  217. - (void)setShootingOrientation:(UIDeviceOrientation)shootingOrientation {
  218. if (_shootingOrientation == shootingOrientation) {
  219. return;
  220. }
  221. _shootingOrientation = shootingOrientation;
  222. }
  223. #pragma mark - EventsHandle
  224. ///启动捕获
  225. - (void)startRunning {
  226. if(!self.session.isRunning) {
  227. [self.session startRunning];
  228. }
  229. [self startUpdateDeviceDirection];
  230. }
  231. ///结束捕获
  232. - (void)stopRunning {
  233. if (self.session.isRunning) {
  234. [self.session stopRunning];
  235. }
  236. [self stopUpdateDeviceDirection];
  237. }
  238. //设置聚焦点和模式 默认连续自动聚焦和自动曝光模式
  239. - (void)focusAtPoint:(CGPoint)focalPoint {
  240. //将UI坐标转化为摄像头坐标 (0,0) -> (1,1)
  241. CGPoint cameraPoint = [self.previewLayer captureDevicePointOfInterestForPoint:focalPoint];
  242. AVCaptureDevice *captureDevice = [self.videoInput device];
  243. NSError * error;
  244. //注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁
  245. if ([captureDevice lockForConfiguration:&error]) {
  246. if ([captureDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
  247. [captureDevice setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
  248. }
  249. if ([captureDevice isFocusPointOfInterestSupported]) {
  250. [captureDevice setFocusPointOfInterest:cameraPoint];
  251. }
  252. //曝光模式
  253. if ([captureDevice isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
  254. [captureDevice setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
  255. }
  256. if ([captureDevice isExposurePointOfInterestSupported]) {
  257. [captureDevice setExposurePointOfInterest:cameraPoint];
  258. }
  259. [captureDevice unlockForConfiguration];
  260. } else {
  261. NSLog(@"设置聚焦点错误:%@", error.localizedDescription);
  262. }
  263. }
  264. //切换前/后置摄像头
  265. - (void)switchsCamera:(AVCaptureDevicePosition)devicePosition {
  266. //当前设备方向
  267. if (self.devicePosition == devicePosition) {
  268. return;
  269. }
  270. AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:[self getCameraDeviceWithPosition:devicePosition] error:nil];
  271. //先开启配置,配置完成后提交配置改变
  272. [self.session beginConfiguration];
  273. //移除原有输入对象
  274. [self.session removeInput:self.videoInput];
  275. //添加新的输入对象
  276. if ([self.session canAddInput:videoInput]) {
  277. [self.session addInput:videoInput];
  278. self.videoInput = videoInput;
  279. }
  280. //视频输入对象发生了改变 视频输出的链接也要重新初始化
  281. AVCaptureConnection * captureConnection = [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo];
  282. if ([captureConnection isVideoStabilizationSupported]) {
  283. //视频稳定模式
  284. captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
  285. }
  286. if (self.devicePosition == AVCaptureDevicePositionFront && captureConnection.supportsVideoMirroring) {
  287. captureConnection.videoMirrored = YES;
  288. }
  289. if (self.shootingOrientation == UIDeviceOrientationLandscapeRight) {
  290. captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  291. } else if (self.shootingOrientation == UIDeviceOrientationLandscapeLeft) {
  292. captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
  293. } else if (self.shootingOrientation == UIDeviceOrientationPortraitUpsideDown) {
  294. captureConnection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
  295. } else {
  296. captureConnection.videoOrientation = AVCaptureVideoOrientationPortrait;
  297. }
  298. //提交新的输入对象
  299. [self.session commitConfiguration];
  300. }
  301. //拍照 输出图片
  302. - (void)outputPhoto {
  303. //获得图片输出连接
  304. AVCaptureConnection * captureConnection = [self.capturePhotoOutput connectionWithMediaType:AVMediaTypeVideo];
  305. // 设置是否为镜像,前置摄像头采集到的数据本来就是翻转的,这里设置为镜像把画面转回来
  306. if (self.devicePosition == AVCaptureDevicePositionFront && captureConnection.supportsVideoMirroring) {
  307. captureConnection.videoMirrored = YES;
  308. }
  309. if (self.shootingOrientation == UIDeviceOrientationLandscapeRight) {
  310. captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  311. } else if (self.shootingOrientation == UIDeviceOrientationLandscapeLeft) {
  312. captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
  313. } else if (self.shootingOrientation == UIDeviceOrientationPortraitUpsideDown) {
  314. captureConnection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
  315. } else {
  316. captureConnection.videoOrientation = AVCaptureVideoOrientationPortrait;
  317. }
  318. //输出样式设置 AVVideoCodecKey:AVVideoCodecJPEG等
  319. AVCapturePhotoSettings *capturePhotoSettings = [AVCapturePhotoSettings photoSettings];
  320. // capturePhotoSettings.highResolutionPhotoEnabled = YES; //高分辨率
  321. capturePhotoSettings.flashMode = _flashMode; //闪光灯 根据环境亮度自动决定是否打开闪光灯
  322. [self.capturePhotoOutput capturePhotoWithSettings:capturePhotoSettings delegate:self];
  323. }
  324. //开始输出视频帧
  325. - (void)startRecordVideoToOutputFileAtPath:(NSString *)path {
  326. //移除重复文件
  327. if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
  328. [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
  329. }
  330. self.outputFileURL = [NSURL fileURLWithPath:path];
  331. [self stopUpdateDeviceDirection];
  332. [self.session beginConfiguration];
  333. //获得视频输出连接
  334. AVCaptureConnection * captureConnection = [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo];
  335. if ([captureConnection isVideoStabilizationSupported]) {
  336. //视频稳定模式
  337. captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
  338. }
  339. // 设置是否为镜像,前置摄像头采集到的数据本来就是翻转的,这里设置为镜像把画面转回来
  340. if (self.devicePosition == AVCaptureDevicePositionFront && captureConnection.supportsVideoMirroring) {
  341. captureConnection.videoMirrored = YES;
  342. }
  343. // 每次切换这个视频输出方向时,会造成摄像头的短暂黑暗? 故暂弃用此方法来设置输出的正确方向
  344. if (self.shootingOrientation == UIDeviceOrientationLandscapeRight) {
  345. captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  346. } else if (self.shootingOrientation == UIDeviceOrientationLandscapeLeft) {
  347. captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
  348. } else if (self.shootingOrientation == UIDeviceOrientationPortraitUpsideDown) {
  349. captureConnection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
  350. } else {
  351. captureConnection.videoOrientation = AVCaptureVideoOrientationPortrait;
  352. }
  353. [self.session commitConfiguration];
  354. //写入视频大小
  355. NSInteger numPixels = SL_kScreenWidth * SL_kScreenHeight;
  356. //每像素比特
  357. CGFloat bitsPerPixel = 12.0;
  358. NSInteger bitsPerSecond = numPixels * bitsPerPixel;
  359. // 码率和帧率设置
  360. NSDictionary *compressionProperties = @{ AVVideoAverageBitRateKey : @(bitsPerSecond),
  361. AVVideoExpectedSourceFrameRateKey : @(15),
  362. AVVideoMaxKeyFrameIntervalKey : @(15),
  363. AVVideoProfileLevelKey : AVVideoProfileLevelH264BaselineAutoLevel };
  364. CGFloat width = SL_kScreenWidth;
  365. CGFloat height = SL_kScreenHeight;
  366. if (self.shootingOrientation == UIDeviceOrientationLandscapeLeft || self.shootingOrientation == UIDeviceOrientationLandscapeRight) {
  367. width = SL_kScreenHeight;
  368. height = SL_kScreenWidth;
  369. }
  370. //视频属性
  371. self.videoCompressionSettings = @{ AVVideoCodecKey : AVVideoCodecH264,
  372. AVVideoWidthKey : @(width * [UIScreen mainScreen].scale),
  373. AVVideoHeightKey : @(height * [UIScreen mainScreen].scale),
  374. AVVideoScalingModeKey : AVVideoScalingModeResizeAspectFill,
  375. AVVideoCompressionPropertiesKey : compressionProperties };
  376. _assetWriterVideoInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:self.videoCompressionSettings];
  377. //expectsMediaDataInRealTime 必须设为yes,需要从capture session 实时获取数据
  378. _assetWriterVideoInput.expectsMediaDataInRealTime = YES;
  379. if ([self.assetWriter canAddInput:_assetWriterVideoInput]) {
  380. [self.assetWriter addInput:_assetWriterVideoInput];
  381. } else {
  382. NSLog(@"视频写入失败");
  383. }
  384. if ([self.assetWriter canAddInput:self.assetWriterAudioInput]) {
  385. [self.assetWriter addInput:self.assetWriterAudioInput];
  386. } else {
  387. NSLog(@"音频写入失败");
  388. }
  389. _isRecording = YES;
  390. }
  391. /// 结束捕获视频帧
  392. - (void)stopRecordVideo {
  393. if (_isRecording) {
  394. _isRecording = NO;
  395. __weak typeof(self) weakSelf = self;
  396. if(_assetWriter && _assetWriter.status == AVAssetWriterStatusWriting) {
  397. [_assetWriter finishWritingWithCompletionHandler:^{
  398. weakSelf.canWrite = NO;
  399. weakSelf.assetWriter = nil;
  400. weakSelf.assetWriterAudioInput = nil;
  401. weakSelf.assetWriterVideoInput = nil;
  402. if ([weakSelf.delegate respondsToSelector:@selector(captureTool:didFinishRecordingToOutputFileAtURL:error:)]) {
  403. DISPATCH_ON_MAIN_THREAD(^{
  404. [weakSelf.delegate captureTool:weakSelf didFinishRecordingToOutputFileAtURL:weakSelf.outputFileURL error:weakSelf.assetWriter.error];
  405. });
  406. }
  407. }];
  408. }
  409. }
  410. }
  411. //开始录制音频
  412. - (void)startRecordAudioToOutputFileAtPath:(NSString *)path {
  413. //移除重复文件
  414. if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
  415. [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
  416. }
  417. self.outputFileURL = [NSURL fileURLWithPath:path];
  418. [self stopUpdateDeviceDirection];
  419. [self.session beginConfiguration];
  420. //移除视频输出对象
  421. [self.session removeOutput:self.videoDataOutput];
  422. [self.session commitConfiguration];
  423. if ([self.assetWriter canAddInput:self.assetWriterAudioInput]) {
  424. [self.assetWriter addInput:self.assetWriterAudioInput];
  425. } else {
  426. NSLog(@"音频写入失败");
  427. }
  428. _isRecording = YES;
  429. }
  430. //结束音频录制
  431. - (void)stopRecordAudio {
  432. if (_isRecording) {
  433. _isRecording = NO;
  434. __weak typeof(self) weakSelf = self;
  435. if(_assetWriter && _assetWriter.status == AVAssetWriterStatusWriting) {
  436. [_assetWriter finishWritingWithCompletionHandler:^{
  437. weakSelf.canWrite = NO;
  438. weakSelf.assetWriter = nil;
  439. weakSelf.assetWriterAudioInput = nil;
  440. weakSelf.assetWriterVideoInput = nil;
  441. if ([weakSelf.delegate respondsToSelector:@selector(captureTool:didFinishRecordingToOutputFileAtURL:error:)]) {
  442. DISPATCH_ON_MAIN_THREAD(^{
  443. [weakSelf.delegate captureTool:weakSelf didFinishRecordingToOutputFileAtURL:weakSelf.outputFileURL error:weakSelf.assetWriter.error];
  444. });
  445. }
  446. }];
  447. }
  448. }
  449. }
  450. #pragma mark - 重力感应监测设备方向
  451. ///开始监听设备方向
  452. - (void)startUpdateDeviceDirection {
  453. if ([self.motionManager isAccelerometerAvailable] == YES) {
  454. //回调会一直调用,建议获取到就调用下面的停止方法,需要再重新开始,当然如果需求是实时不间断的话可以等离开页面之后再stop
  455. [self.motionManager setAccelerometerUpdateInterval:1.0];
  456. __weak typeof(self) weakSelf = self;
  457. [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
  458. double x = accelerometerData.acceleration.x;
  459. double y = accelerometerData.acceleration.y;
  460. if ((fabs(y) + 0.1f) >= fabs(x)) {
  461. if (y >= 0.1f) {
  462. // NSLog(@"Down");
  463. weakSelf.shootingOrientation = UIDeviceOrientationPortraitUpsideDown;
  464. } else {
  465. // NSLog(@"Portrait");
  466. weakSelf.shootingOrientation = UIDeviceOrientationPortrait;
  467. }
  468. } else {
  469. if (x >= 0.1f) {
  470. // NSLog(@"Right");
  471. weakSelf.shootingOrientation = UIDeviceOrientationLandscapeRight;
  472. } else if (x <= 0.1f) {
  473. // NSLog(@"Left");
  474. weakSelf.shootingOrientation = UIDeviceOrientationLandscapeLeft;
  475. } else {
  476. // NSLog(@"Portrait");
  477. weakSelf.shootingOrientation = UIDeviceOrientationPortrait;
  478. }
  479. }
  480. }];
  481. }
  482. }
  483. /// 停止监测方向
  484. - (void)stopUpdateDeviceDirection {
  485. if ([self.motionManager isAccelerometerActive] == YES) {
  486. [self.motionManager stopAccelerometerUpdates];
  487. _motionManager = nil;
  488. }
  489. }
  490. #pragma mark - AVCapturePhotoCaptureDelegate 图片输出代理
  491. /// 捕获拍摄图片的回调
  492. - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(nullable NSError *)error API_AVAILABLE(ios(11.0)) {
  493. NSData *data = [photo fileDataRepresentation];
  494. UIImage *image = [UIImage imageWithData:data];
  495. if ([self.delegate respondsToSelector:@selector(captureTool:didOutputPhoto:error:)]) {
  496. [self.delegate captureTool:self didOutputPhoto:image error:error];
  497. }else {
  498. NSLog(@"请实现代理方法:captureTool:didOutputPhoto:error:");
  499. }
  500. }
  501. #pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate AVCaptureAudioDataOutputSampleBufferDelegate 实时输出帧内容
  502. /// 实时输出音视频帧内容
  503. - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  504. if(!_isRecording || sampleBuffer == NULL) {
  505. return;
  506. }
  507. @autoreleasepool {
  508. //视频
  509. if (output == self.videoDataOutput) {
  510. @synchronized(self) {
  511. if (!self.canWrite) {
  512. [self.assetWriter startWriting];
  513. [self.assetWriter startSessionAtSourceTime:CMSampleBufferGetPresentationTimeStamp(sampleBuffer)];
  514. self.canWrite = YES;
  515. }
  516. //写入视频数据
  517. if (self.assetWriterVideoInput.readyForMoreMediaData) {
  518. BOOL success = [self.assetWriterVideoInput appendSampleBuffer:sampleBuffer];
  519. if (!success) {
  520. @synchronized (self) {
  521. [self stopRecordVideo];
  522. }
  523. }
  524. }
  525. }
  526. }
  527. //音频
  528. if (output == self.audioDataOutput) {
  529. @synchronized(self) {
  530. if (!self.canWrite) {
  531. [self.assetWriter startWriting];
  532. [self.assetWriter startSessionAtSourceTime:CMSampleBufferGetPresentationTimeStamp(sampleBuffer)];
  533. self.canWrite = YES;
  534. }
  535. if (self.assetWriterAudioInput.readyForMoreMediaData) {
  536. //写入音频数据
  537. BOOL success = [self.assetWriterAudioInput appendSampleBuffer:sampleBuffer];
  538. if (!success) {
  539. @synchronized (self) {
  540. [self stopRecordVideo];
  541. }
  542. }
  543. }
  544. }
  545. }
  546. }
  547. }
  548. @end