最近在处理一些基于GPUImage视频录制的功能,在保存文档的时候选用AVFileTypeMPEG4格式会出现错误。

  • Couldn’t write a frame
  • Couldn’t write a frame when use AVFileTypeMPEG4 type to record

仔细阅读了一下GPUImageMovieWriter的文件发现里面有一段实用的注释:

比如:

NSMutableDictionary *outputSettings = [NSMutableDictionary dictionary];
NSDictionary *videoCleanApertureSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                            [NSNumber numberWithInt:kVideoWidth], AVVideoCleanApertureWidthKey,
                                            [NSNumber numberWithInt:kVideoHeight], AVVideoCleanApertureHeightKey,
                                            [NSNumber numberWithInt:0], AVVideoCleanApertureHorizontalOffsetKey,
                                            [NSNumber numberWithInt:0], AVVideoCleanApertureVerticalOffsetKey,
                                            nil];

NSDictionary *videoAspectRatioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [NSNumber numberWithInt:3], AVVideoPixelAspectRatioHorizontalSpacingKey,
                                          [NSNumber numberWithInt:3], AVVideoPixelAspectRatioVerticalSpacingKey,
                                          nil];

NSMutableDictionary * compressionProperties = [[NSMutableDictionary alloc] init];
[compressionProperties setObject:videoCleanApertureSettings forKey:AVVideoCleanApertureKey];
[compressionProperties setObject:videoAspectRatioSettings forKey:AVVideoPixelAspectRatioKey];
[compressionProperties setObject:[NSNumber numberWithInt: 1000000] forKey:AVVideoAverageBitRateKey];
[compressionProperties setObject:[NSNumber numberWithInt: 20] forKey:AVVideoMaxKeyFrameIntervalKey];
[compressionProperties setObject:AVVideoProfileLevelH264Main31 forKey:AVVideoProfileLevelKey];

[outputSettings setObject:compressionProperties forKey:AVVideoCompressionPropertiesKey];
[outputSettings setObject:AVVideoCodecH264 forKey:AVVideoCodecKey];
[outputSettings setObject:[NSNumber numberWithInt:kVideoWidth] forKey:AVVideoWidthKey];
[outputSettings setObject:[NSNumber numberWithInt:kVideoHeight] forKey:AVVideoHeightKey];

其中AVVideoAverageBitRateKey可以控制输出视频的质量&文件大小

参考资料:
1. the reason for error “Couldn’t write a frame” when record a movie? #1729
2. Couldn’t write a frame when use AVFileTypeMPEG4 type to record #2264
3. the reason for error “Couldn’t write a frame” when record a movie? #1729