iOS 开发中 通过AVAssetWriter将录像视频写到指定文件
2019独角兽企业重金招聘Python工程师标准>>>
转自:http://flhs-wdw.blog.sohu.com/207300574.html
iphone提供了AVFoundation库来方便的操作多媒体设备,AVAssetWriter这个类可以方便的将图像和音频写成一个完整的视频文件。甚至将整个应用的操作录制下来,也不是什么困难的事情。
- NSError * error;
- session = [[AVCaptureSession alloc] init];
- [session beginConfiguration];
- [session setSessionPreset:AVCaptureSessionPreset640x480];
- [self initVideoAudioWriter];
- AVCaptureDevice * videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
- AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
- AVCaptureDevice * audioDevice1 = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
- AVCaptureDeviceInput *audioInput1 = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice1 error:&error];
- videoOutput = [[AVCaptureVideoDataOutput alloc] init];
- [videoOutput setAlwaysDiscardsLateVideoFrames:YES];
- [videoOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA]forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
- [videoOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
- audioOutput = [[AVCaptureAudioDataOutput alloc] init];
- numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
- [audioOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
- [session addInput:videoInput];
- [session addInput:audioInput1];
- [session addOutput:videoOutput];
- [session addOutput:audioOutput];
- [session commitConfiguration];
- [session startRunning];
回调函数:
- -(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
- //CVPixelBufferRef pixelBuffer = (CVPixelBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);
- NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
- static int frame = 0;
- CMTime lastSampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
- if( frame == 0 && videoWriter.status != AVAssetWriterStatusWriting )
- {
- [videoWriter startWriting];
- [videoWriter startSessionAtSourceTime:lastSampleTime];
- }
- if (captureOutput == videoOutput)
- {
- / if( videoWriter.status > AVAssetWriterStatusWriting )
- {
- NSLog(@"Warning: writer status is %d", videoWriter.status);
- if( videoWriter.status == AVAssetWriterStatusFailed )
- NSLog(@"Error: %@", videoWriter.error);
- return;
- }
- if ([videoWriterInput isReadyForMoreMediaData])
- if( ![videoWriterInput appendSampleBuffer:sampleBuffer] )
- NSLog(@"Unable to write to video input");
- else
- NSLog(@"already write vidio");
- }
- }
- else if (captureOutput == audioOutput)
- {
- if( videoWriter.status > AVAssetWriterStatusWriting )
- {
- NSLog(@"Warning: writer status is %d", videoWriter.status);
- if( videoWriter.status == AVAssetWriterStatusFailed )
- NSLog(@"Error: %@", videoWriter.error);
- return;
- }
- if ([audioWriterInput isReadyForMoreMediaData])
- if( ![audioWriterInput appendSampleBuffer:sampleBuffer] )
- NSLog(@"Unable to write to audio input");
- else
- NSLog(@"already write audio");
- }
- if (frame == FrameCount)
- {
- [self closeVideoWriter];
- }
- frame ++;
- [pool drain];
- }
剩下的工作就是初始化AVAssetWriter,包括音频与视频输入输出:
- -(void) initVideoAudioWriter
- {
- CGSize size = CGSizeMake(480, 320);
- NSString *betaCompressionDirectory = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents/Movie.mp4"];
- NSError *error = nil;
- unlink([betaCompressionDirectory UTF8String]);
- //----initialize compression engine
- self.videoWriter = [[AVAssetWriter alloc] initWithURL:[NSURLfileURLWithPath:betaCompressionDirectory]
- fileType:AVFileTypeQuickTimeMovie
- error:&error];
- NSParameterAssert(videoWriter);
- if(error)
- NSLog(@"error = %@", [error localizedDescription]);
- NSDictionary *videoCompressionProps = [NSDictionary dictionaryWithObjectsAndKeys:
- [NSNumber numberWithDouble:128.0*1024.0],AVVideoAverageBitRateKey,
- nil ];
- NSDictionary *videoSettings = [NSDictionarydictionaryWithObjectsAndKeys:AVVideoCodecH264, AVVideoCodecKey,
- [NSNumber numberWithInt:size.width], AVVideoWidthKey,
- [NSNumber numberWithInt:size.height],AVVideoHeightKey,videoCompressionProps, AVVideoCompressionPropertiesKey, nil];
- self.videoWriterInput = [AVAssetWriterInputassetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
- NSParameterAssert(videoWriterInput);
- videoWriterInput.expectsMediaDataInRealTime = YES;
- NSDictionary *sourcePixelBufferAttributesDictionary = [NSDictionarydictionaryWithObjectsAndKeys:
- [NSNumbernumberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];
- self.adaptor = [AVAssetWriterInputPixelBufferAdaptorassetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput
- sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary];
- NSParameterAssert(videoWriterInput);
- NSParameterAssert([videoWriter canAddInput:videoWriterInput]);
- if ([videoWriter canAddInput:videoWriterInput])
- NSLog(@"I can add this input");
- else
- NSLog(@"i can't add this input");
- // Add the audio input
- AudioChannelLayout acl;
- bzero( &acl, sizeof(acl));
- acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
- NSDictionary* audioOutputSettings = nil;
- // audioOutputSettings = [ NSDictionary dictionaryWithObjectsAndKeys:
- // [ NSNumber numberWithInt: kAudioFormatAppleLossless ], AVFormatIDKey,
- // [ NSNumber numberWithInt: 16 ], AVEncoderBitDepthHintKey,
- // [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
- // [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
- // [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
- // nil ];
- audioOutputSettings = [ NSDictionary dictionaryWithObjectsAndKeys:
- [ NSNumber numberWithInt: kAudioFormatMPEG4AAC ], AVFormatIDKey,
- [ NSNumber numberWithInt:64000], AVEncoderBitRateKey,
- [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
- [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
- [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
- nil ];
- audioWriterInput = [[AVAssetWriterInput
- assetWriterInputWithMediaType: AVMediaTypeAudio
- outputSettings: audioOutputSettings ] retain];
- audioWriterInput.expectsMediaDataInRealTime = YES;
- // add input
- [videoWriter addInput:audioWriterInput];
- [videoWriter addInput:videoWriterInput];
- }
转载于:https://my.oschina.net/u/1049180/blog/137802
iOS 开发中 通过AVAssetWriter将录像视频写到指定文件相关推荐
- iOS开发中的神兵利器 [实战系列]-李发展-专题视频课程
iOS开发中的神兵利器 [实战系列]-11758人已学习 课程介绍 - 140节课程讲解GitHub中近百个过千star的iOS热门开源项目 - 市面上唯一大规模讲解热门的iOS开源项 ...
- iOS开发中didSelectRowAtIndexPath tap事件响应延迟
iOS开发中didSelectRowAtIndexPath tap事件响应延迟 为UITableViewCell添加tapped事件,代码如下: class VideoViewController: ...
- iOS开发中的Web应用概述
为了更好的阅读体验,建议阅读原文 插播广告 -- 几十行代码完成资讯类App多种形式内容页 HybridPageKit :一个针对资讯类App高性能.易扩展.组件化的通用内容页实现框架. 想和我一起全 ...
- FFmpeg在iOS开发中编译并使用
FFmpeg简介 FFmpeg是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.读作:爱服爱服爱母派格.全称:Fast Forward Mpeg.直译:快速转换图像.FFmpe ...
- iOS开发中遇到的一些问题及解决方案【转载】
iOS开发中遇到的一些问题及解决方案[转载] 2015-12-29 [385][scrollView不接受点击事件,是因为事件传递失败] // // MyScrollView.m // Creat ...
- iOS开发中屏幕旋转(一)
Morris_ 2018.11.24 前言 最近做一个关于在线视频互动的iPad项目,部分界面只要横屏,部分界面可以横竖屏转换.看了看别家做的项目,有些是只做竖/横屏,有些是支持了横竖屏转换,在iPa ...
- ios 开发中 动态库 与静态库的区别
使用静态库的好处 1,模块化,分工合作 2,避免少量改动经常导致大量的重复编译连接 3,也可以重用,注意不是共享使用 动态库使用有如下好处: 1使用动态库,可以将最终可执行文件体积缩小 2使用动态库, ...
- iOS 开发中的多线程
线程.进程 什么是线程.进程 有的人说进程就像是人的脑袋,线程就是脑袋上的头发~~.其实这么比方不算错,但是更简单的来说,用迅雷下载文件,迅雷这个程序就是一个进程,下载的文件就是一个线程,同时下载 ...
- iOS开发中使用[[UIApplication sharedApplication] openURL:]加载其它应用
iOS 应用程序之间(1) 在iOS开发中,经常需要调用其它App,如拨打电话.发送邮件等.UIApplication:openURL:方法是实现这一目的的最简单方法,该方法一般通过提供的url参数的 ...
- iOS开发中各种关键字的区别
1.一些概念 1.浅Copy:指针的复制,只是多了一个指向这块内存的指针,共用一块内存. 深Copy:内存的复制,两块内存是完全不同的, 也就是两个对象指针分别指向不同的内存,互不干涉. 2.atom ...
最新文章
- 串口 能 按位传输吗_六类网线能传输多少米?家装六类网线有必要吗?
- plotly可视化绘制多图(multiplot)
- 总结FormsAuthentication的使用
- legend3---4、lavarel中session使用注意
- OSI模型中的数据链路层和物理层的区分
- Android NDK 内存泄露检测
- java集合框架03
- 配置MGR时修改了/etc/hosts但映射后的hostname不起作用
- 错误ORA-04091: table is mutating, trigger/function may not see it的原因以及解决办法
- 本地---tcpserver与tcpclient
- jQuery Ajax POST方法
- 基于jquery的从一个页面跳转到另一个页面的指定位置的实现代码
- LNMP详解(六)——Nginx location语法详解
- python3.x编程模板总结
- java int 位_java int是几位
- MATLAB代码:基于分布式ADMM算法的考虑碳排放交易的电力系统优化调度研究
- 【DIY】通达信DIY添加扫雷宝、地图和复盘(1)
- ps去水印教程_Adobe Photoshop CS2去除水印方法 PS去水印教程
- SmartUpload文件上传
- mysql ndb_MySQL NDB Cluster概述
热门文章
- yolov4网络结构_上达最高精度,下到最快速度,Scaled-YOLOv4:模型缩放显神威
- 八爪鱼导出到mysql数据库_数据导出到Oracle数据库的方法 - 八爪鱼采集器
- android连mysql注册界面代码_Android实现注册登录界面的实例代码
- Vite 配置项目别名-最新版
- React Native 介绍
- MTK平台修改分区大小之后,通过fastboot工具烧录的说明
- 播报哥架构运行异常提示
- Java Servlet(十一):一个servlet被10个浏览器客户端访问时会创建几个servlet实例?...
- Spring常用注解用法总结
- javascript简介和基本语法