WCLRecordEncoder.mm 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. //
  2. // WCLRecordEncoder.m
  3. // WCL
  4. //
  5. // **************************************************
  6. // * _____ *
  7. // * __ _ __ ___ \ / *
  8. // * \ \/ \/ / / __\ / / *
  9. // * \ _ / | (__ / / *
  10. // * \/ \/ \___/ / /__ *
  11. // * /_____/ *
  12. // * *
  13. // **************************************************
  14. // Github :https://github.com/631106979
  15. // HomePage:https://imwcl.com
  16. // CSDN :http://blog.csdn.net/wang631106979
  17. //
  18. // Created by 王崇磊 on 16/9/14.
  19. // Copyright © 2016年 王崇磊. All rights reserved.
  20. //
  21. // @class WCLRecordEncoder
  22. // @abstract 视频编码类
  23. // @discussion 应用的相关扩展
  24. //
  25. // 博客地址:http://blog.csdn.net/wang631106979/article/details/51498009
  26. #import "WCLRecordEncoder.h"
  27. @interface WCLRecordEncoder ()
  28. {
  29. NSMutableData *soundTouchDatas;
  30. NSMutableData *cacheData;
  31. }
  32. //@property (nonatomic, strong) AVAssetWriter *writer;//媒体写入对象
  33. @property (nonatomic, strong) AVAssetWriterInput *videoInput;//视频写入
  34. @property (nonatomic, strong) AVAssetWriterInput *audioInput;//音频写入
  35. @property (nonatomic, strong) NSString *path;//写入路径
  36. @property(strong,nonatomic)AVAssetWriterInputPixelBufferAdaptor *adaptor;
  37. @end
  38. @implementation WCLRecordEncoder
  39. - (void)dealloc {
  40. _writer = nil;
  41. _videoInput = nil;
  42. _audioInput = nil;
  43. _path = nil;
  44. soundTouchDatas = nil;
  45. cacheData = nil;
  46. }
  47. //WCLRecordEncoder遍历构造器的
  48. + (WCLRecordEncoder*)encoderForPath:(NSString*) path Height:(NSInteger) cy width:(NSInteger) cx channels: (int) ch samples:(Float64) rate {
  49. WCLRecordEncoder* enc = [WCLRecordEncoder alloc];
  50. return [enc initPath:path Height:cy width:cx channels:ch samples:rate];
  51. }
  52. //初始化方法
  53. - (instancetype)initPath:(NSString*)path Height:(NSInteger)cy width:(NSInteger)cx channels:(int)ch samples:(Float64) rate {
  54. self = [super init];
  55. if (self) {
  56. self.path = path;
  57. //先把路径下的文件给删除掉,保证录制的文件是最新的
  58. [[NSFileManager defaultManager] removeItemAtPath:self.path error:nil];
  59. NSURL* url = [NSURL fileURLWithPath:self.path];
  60. //初始化写入媒体类型为MP4类型
  61. _writer = [AVAssetWriter assetWriterWithURL:url fileType:AVFileTypeMPEG4 error:nil];
  62. //使其更适合在网络上播放
  63. _writer.shouldOptimizeForNetworkUse = YES;
  64. //初始化视频输出
  65. [self initVideoInputHeight:cy width:cx];
  66. //确保采集到rate和ch
  67. if (rate != 0 && ch != 0) {
  68. //初始化音频输出
  69. [self initAudioInputChannels:ch samples:rate];
  70. }
  71. // soundTouchDatas = [[NSMutableData alloc] init];
  72. // cacheData = [[NSMutableData alloc] init];
  73. }
  74. return self;
  75. }
  76. //初始化视频输入
  77. - (void)initVideoInputHeight:(NSInteger)cy width:(NSInteger)cx {
  78. //录制视频的一些配置,分辨率,编码方式等等
  79. NSDictionary* settings = [NSDictionary dictionaryWithObjectsAndKeys:
  80. AVVideoCodecH264, AVVideoCodecKey,
  81. [NSNumber numberWithInteger: cx], AVVideoWidthKey,
  82. [NSNumber numberWithInteger: cy], AVVideoHeightKey,
  83. nil];
  84. //初始化视频写入类
  85. _videoInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];
  86. //表明输入是否应该调整其处理为实时数据源的数据
  87. _videoInput.expectsMediaDataInRealTime = YES;
  88. NSDictionary *sourcePixelBufferAttributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kCVPixelFormatType_32BGRA], kCVPixelBufferPixelFormatTypeKey,
  89. [NSNumber numberWithInt:(int)cx], kCVPixelBufferWidthKey,
  90. [NSNumber numberWithInt:(int)cy], kCVPixelBufferHeightKey,
  91. nil];
  92. _adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:_videoInput
  93. sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary];
  94. //将视频输入源加入
  95. [_writer addInput:_videoInput];
  96. }
  97. //初始化音频输入
  98. - (void)initAudioInputChannels:(int)ch samples:(Float64)rate {
  99. AudioChannelLayout acl;
  100. bzero( &acl, sizeof(acl));
  101. acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
  102. //音频的一些配置包括音频各种这里为AAC,音频通道、采样率和音频的比特率
  103. NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
  104. [ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
  105. [ NSNumber numberWithInt: ch], AVNumberOfChannelsKey,
  106. [ NSNumber numberWithFloat: rate], AVSampleRateKey,
  107. [ NSNumber numberWithInt: 64000], AVEncoderBitRateKey,
  108. [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
  109. nil];
  110. //初始化音频写入类
  111. _audioInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:settings];
  112. //表明输入是否应该调整其处理为实时数据源的数据
  113. _audioInput.expectsMediaDataInRealTime = YES;
  114. //将音频输入源加入
  115. [_writer addInput:_audioInput];
  116. }
  117. //完成视频录制时调用
  118. - (void)finishWithCompletionHandler:(void (^)(void))handler {
  119. if (_writer.status == AVAssetWriterStatusCompleted || _writer.status == AVAssetWriterStatusCancelled || _writer.status == AVAssetWriterStatusUnknown)
  120. {
  121. if (handler)
  122. handler();
  123. return;
  124. }
  125. if( _writer.status == AVAssetWriterStatusWriting )
  126. {
  127. [_audioInput markAsFinished];
  128. [_videoInput markAsFinished];
  129. }
  130. [_writer finishWritingWithCompletionHandler:handler];
  131. }
  132. //通过这个方法写入数据
  133. - (BOOL)encodeFrame:(CMSampleBufferRef)sampleBuffer pixelBuffer:(CVPixelBufferRef)buffer isVideo:(BOOL)isVideo {
  134. //数据是否准备写入
  135. if (CMSampleBufferDataIsReady(sampleBuffer)) {
  136. //写入状态为未知,保证视频先写入
  137. if (_writer.status == AVAssetWriterStatusUnknown && isVideo) {
  138. //获取开始写入的CMTime
  139. CMTime startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
  140. //开始写入
  141. [_writer startWriting];
  142. [_writer startSessionAtSourceTime:startTime];
  143. }
  144. //写入失败
  145. if (_writer.status == AVAssetWriterStatusFailed) {
  146. NSLog(@"writer error %@", _writer.error.localizedDescription);
  147. return NO;
  148. }
  149. if (_writer.status == AVAssetWriterStatusCancelled || _writer.status == AVAssetWriterStatusCompleted) {
  150. return YES;
  151. }
  152. //判断是否是视频
  153. if (isVideo) {
  154. //视频输入是否准备接受更多的媒体数据
  155. if (_videoInput.readyForMoreMediaData == YES && _writer.status == AVAssetWriterStatusWriting) {
  156. // //拼接数据
  157. //// [_videoInput appendSampleBuffer:sampleBuffer];
  158. // CVPixelBufferLockBaseAddress(buffer, 0);
  159. //
  160. // int h = (int)CVPixelBufferGetHeight(buffer);
  161. //
  162. // int stride = (int)CVPixelBufferGetBytesPerRow(buffer);
  163. //
  164. // int* img = (int*)CVPixelBufferGetBaseAddress(buffer);
  165. //
  166. // for (int x = 0; x < stride/4; x++){
  167. //
  168. // for (int y = 0; y < h; y++){
  169. //
  170. // img[y * stride/4 + x] |= 0xff000000;
  171. //
  172. // }
  173. // }
  174. // CVPixelBufferUnlockBaseAddress(buffer, 0);
  175. CMTime currentSampleTime = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer);
  176. [_adaptor appendPixelBuffer:buffer withPresentationTime:currentSampleTime];
  177. return YES;
  178. }
  179. }else {
  180. //音频输入是否准备接受更多的媒体数据
  181. if (_audioInput.readyForMoreMediaData && _writer.status == AVAssetWriterStatusWriting) {
  182. //拼接数据
  183. [_audioInput appendSampleBuffer:sampleBuffer];
  184. return YES;
  185. }
  186. }
  187. }
  188. return NO;
  189. }
  190. @end