1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| - (void)setupVideoSession { // 1.用于记录当前是第几帧数据(画面帧数非常多) self.frameID = 0;
// 2.录制视频的宽度&高度 int width = [UIScreen mainScreen].bounds.size.width; int height = [UIScreen mainScreen].bounds.size.height;
// 3.创建CompressionSession对象,该对象用于对画面进行编码 // kCMVideoCodecType_H264 : 表示使用h.264进行编码 // didCompressH264 : 当一次编码结束会在该函数进行回调,可以在该函数中将数据,写入文件中 VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressH264, (__bridge void *)(self), &_compressionSession);
// 4.设置实时编码输出(直播必然是实时输出,否则会有延迟) VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
// 5.设置期望帧率(每秒多少帧,如果帧率过低,会造成画面卡顿) int fps = 30; CFNumberRef fpsRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &fps); VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_ExpectedFrameRate, fpsRef);
// 6.设置码率(码率: 编码效率, 码率越高,则画面越清晰, 如果码率较低会引起马赛克 --> 码率高有利于还原原始画面,但是也不利于传输) int bitRate = 800*1024; CFNumberRef bitRateRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRate); VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_AverageBitRate, bitRateRef); NSArray *limit = @[@(bitRate * 1.5/8), @(1)]; VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_DataRateLimits, (__bridge CFArrayRef)limit);
// 7.设置关键帧(GOPsize)间隔 int frameInterval = 30; CFNumberRef frameIntervalRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frameInterval); VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, frameIntervalRef);
// 8.基本设置结束, 准备进行编码 VTCompressionSessionPrepareToEncodeFrames(self.compressionSession); }
|