iOS AVAssetWriter 实现高分辨率录制视频,生成低体积的视频文件

在实现小视频录制功能的时候,如果单纯的使用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/LXFAVFoundation

 

 

 

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值