在实现小视频录制功能的时候,如果单纯的使用AVCaptureMovieFileOutput将录制的视频文件进行输出,则会导致录制的视频文件太过于大。对于拍摄质量要求较高且要上传到服务器的小视频的APP对用户来说则显得不友好。这里使用AVAssetWriter对录制视频的输出流进行了处理。
self.assetWriter = [AVAssetWriter assetWriterWithURL:self.videoURL fileType:AVFileTypeMPEG4 error:nil];
//写入视频大小
NSInteger numPixels = kScreenWidth * kScreenHeight;
//每像素比特
CGFloat bitsPerPixel = 6.0;
NSInteger bitsPerSecond = numPixels * bitsPerPixel;
// 码率和帧率设置
NSDictionary *compressionProperties = @{ AVVideoAverageBitRateKey : @(bitsPerSecond),
AVVideoExpectedSourceFrameRateKey : @(15),
AVVideoMaxKeyFrameIntervalKey : @(15),
AVVideoProfileLevelKey : AVVideoProfileLevelH264BaselineAutoLevel };
//视频属性
self.videoCompressionSettings = @{ AVVideoCodecKey : AVVideoCodecH264,
AVVideoScalingModeKey : AVVideoScalingModeResizeAspectFill,
AVVideoWidthKey : @(kScreenHeight * 2),
AVVideoHeightKey : @(kScreenWidth * 2),
AVVideoCompressionPropertiesKey : compressionProperties };
_assetWriterVideoInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:self.videoCompressionSettings];
//expectsMediaDataInRealTime 必须设为yes,需要从capture session 实时获取数据
_assetWriterVideoInput.expectsMediaDataInRealTime = YES;
_assetWriterVideoInput.transform = CGAffineTransformMakeRotation(M_PI / 2.0);
// 音频设置
self.audioCompressionSettings = @{ AVEncoderBitRatePerChannelKey : @(28000),
AVFormatIDKey : @(kAudioFormatMPEG4AAC),
AVNumberOfChannelsKey : @(1),
AVSampleRateKey : @(22050) };
_assetWriterAudioInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:self.audioCompressionSettings];
_assetWriterAudioInput.expectsMediaDataInRealTime = YES;
if ([_assetWriter canAddInput:_assetWriterVideoInput])
{
[_assetWriter addInput:_assetWriterVideoInput];
}
else
{
NSLog(@"AssetWriter videoInput append Failed");
}
if ([_assetWriter canAddInput:_assetWriterAudioInput])
{
[_assetWriter addInput:_assetWriterAudioInput];
}
else
{
NSLog(@"AssetWriter audioInput Append Failed");
}
并通过实现代理
AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate的
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection方法,对视频流进行保存处理
详细代码请看我的github,仿制微信的小视频录制功能
https://github.com/LingLemon/XFAVFoundation