使用AVCaptureSession捕捉视频
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h> @interface ViewController : UIViewController<AVCaptureFileOutputRecordingDelegate> @property (strong, nonatomic) AVCaptureSession *captureSession;
@property (strong, nonatomic) AVCaptureDeviceInput *videoInput;
@property (strong, nonatomic) AVCaptureDeviceInput *audioInput;
@property (strong, nonatomic) AVCaptureStillImageOutput *stillImageOutput;
@property (strong, nonatomic) AVCaptureMovieFileOutput *movieOutput; @property (weak, nonatomic) IBOutlet UIButton *captureButton;
@property (weak, nonatomic) IBOutlet UISegmentedControl *modeControl; - (IBAction)capture:(id)sender;
- (IBAction)updateMode:(id)sender; @end
#import "ViewController.h" @interface ViewController () @end @implementation ViewController
@synthesize captureButton;
@synthesize modeControl; - (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.captureSession = [[AVCaptureSession alloc] init];
//Optional: self.captureSession.sessionPreset = AVCaptureSessionPresetMedium; AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
self.audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioDevice error:nil]; self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *stillImageOutputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
AVVideoCodecJPEG, AVVideoCodecKey, nil];
[self.stillImageOutput setOutputSettings:stillImageOutputSettings]; self.movieOutput = [[AVCaptureMovieFileOutput alloc] init]; // Setup capture session for taking pictures
[self.captureSession addInput:self.videoInput];
[self.captureSession addOutput:self.stillImageOutput]; AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
UIView *aView = self.view;
previewLayer.frame = CGRectMake(, , self.view.frame.size.width, self.view.frame.size.height-);
[aView.layer addSublayer:previewLayer];
} - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} - (void) captureStillImage
{
AVCaptureConnection *stillImageConnection = [self.stillImageOutput.connections objectAtIndex:];
if ([stillImageConnection isVideoOrientationSupported])
[stillImageConnection setVideoOrientation:AVCaptureVideoOrientationPortrait]; [[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:stillImageConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
if (imageDataSampleBuffer != NULL)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
UIImage *image = [[UIImage alloc] initWithData:imageData];
[library writeImageToSavedPhotosAlbum:[image CGImage]
orientation:(ALAssetOrientation)[image imageOrientation]
completionBlock:^(NSURL *assetURL, NSError *error)
{
UIAlertView *alert;
if (!error)
{
alert = [[UIAlertView alloc] initWithTitle:@"Photo Saved"
message:@"The photo was successfully saved to you photos library"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
}
else
{
alert = [[UIAlertView alloc] initWithTitle:@"Error Saving Photo"
message:@"The photo was not saved to you photos library"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
} [alert show];
}
];
}
else
NSLog(@"Error capturing still image: %@", error);
}];
} - (NSURL *) tempFileURL
{
NSString *outputPath = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), @"output.mov"];
NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
NSFileManager *manager = [[NSFileManager alloc] init];
if ([manager fileExistsAtPath:outputPath])
{
[manager removeItemAtPath:outputPath error:nil];
}
return outputURL;
} - (IBAction)capture:(id)sender
{
if (self.modeControl.selectedSegmentIndex == 0)
{
// Picture Mode
[self captureStillImage];
}
else
{
// Video Mode
if (self.movieOutput.isRecording == YES)
{
[self.captureButton setTitle:@"Capture" forState:UIControlStateNormal];
[self.movieOutput stopRecording];
}
else
{
[self.captureButton setTitle:@"Stop" forState:UIControlStateNormal];
[self.movieOutput startRecordingToOutputFileURL:[self tempFileURL] recordingDelegate:self];
}
}
} - (IBAction)updateMode:(id)sender
{
[self.captureSession stopRunning];
if (self.modeControl.selectedSegmentIndex == )
{
if (self.movieOutput.isRecording == YES)
{
[self.movieOutput stopRecording];
}
// Picture Mode
[self.captureSession removeInput:self.audioInput];
[self.captureSession removeOutput:self.movieOutput];
[self.captureSession addOutput:self.stillImageOutput];
}
else
{
// Video Mode
[self.captureSession removeOutput:self.stillImageOutput];
[self.captureSession addInput:self.audioInput];
[self.captureSession addOutput:self.movieOutput]; // Set orientation of capture connections to portrait
NSArray *array = [[self.captureSession.outputs objectAtIndex:] connections];
for (AVCaptureConnection *connection in array)
{
connection.videoOrientation = AVCaptureVideoOrientationPortrait;
}
}
[self.captureButton setTitle:@"Capture" forState:UIControlStateNormal]; [self.captureSession startRunning];
} - (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.captureSession startRunning];
} - (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.captureSession stopRunning];
} - (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
BOOL recordedSuccessfully = YES;
if ([error code] != noErr)
{
// A problem occurred: Find out if the recording was successful.
id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
if (value)
recordedSuccessfully = [value boolValue];
// Logging the problem anyway:
NSLog(@"A problem occurred while recording: %@", error);
}
if (recordedSuccessfully) {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosAlbum:outputFileURL
completionBlock:^(NSURL *assetURL, NSError *error)
{
UIAlertView *alert;
if (!error)
{
alert = [[UIAlertView alloc] initWithTitle:@"Video Saved"
message:@"The movie was successfully saved to you photos library"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
}
else
{
alert = [[UIAlertView alloc] initWithTitle:@"Error Saving Video"
message:@"The movie was not saved to you photos library"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
} [alert show];
}
];
}
}
@end
使用AVCaptureSession捕捉视频的更多相关文章
- selenium捕捉视频
捕捉视频 有时候我们未必能够分析故障只需用日志文件或截图的帮助.有时捕获完整的执行视频帮助.让我们了解如何捕捉视频. 我们将利用Monte媒体库的执行相同. 配置 第1步:导航到URL - http: ...
- CSS canvas 捕捉视频video元素截图
video元素介绍: http://www.runoob.com/html/html5-video.html https://developer.mozilla.org/zh-CN/docs/Web/ ...
- AVCaptureSession音频视频采集
// // AudioVideoCaptureViewController.m // live // // Created by lujunjie on 2016/10/31. // Copyrigh ...
- iOS AVCaptureSession 小视频开发总结,支持设备旋转
iOS开发中当我们想要自定义相机拍照或摄像界面时,UIImagePickerController无法满足我们的需求,这时候我们可以使用AVFoundation.framework这个framework ...
- 使用AVCaptureSession捕捉静态图片
#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <AssetsLibrary/ ...
- 如何在视频处理控件TVideoGrabber中设置音频捕捉设备
TVideoGrabber不仅可以捕捉视频,还可以作为多媒体播放器,并支持包括C#..NET.VB.NET.C++.Delphi.C++Builder和ActiveX平台,本文将剖析TVideoGra ...
- 视频捕捉全教程(vc+vfw)
目 录 一. 视频捕获快速入门 二.基本的捕获设置 1.设置捕获速度: 2.设置终止捕获 3.捕获的时间限制 三.关于捕获窗口 1.创建一个AVICAP捕获窗口 2.将一个捕获窗口连接至捕获设备 3. ...
- VirtualDub - 开源视频捕捉及线性处理软件
VirtualDub是一个开放源代码的视频捕捉及线性处理软件.它由Avery Lee编写,遵循GPL协议.VirtualDub可以通过摄像头捕捉视频. 官方网站http://virtualdub.or ...
- Direcshow中视频捕捉和参数设置报告
Direcshow中视频捕捉和参数设置报告 1. 关于视频捕捉(About Video Capture in Dshow) 1视频捕捉Graph的构建 一个能够捕捉音频或者视频的graph图 ...
随机推荐
- cygwin使用
Cygwin是一个在windows平台上运行的类UNIX模拟环境,是cygnus solutions公司开发的自由软件(该公司开发的著名工具还有eCos,不过现已被Redhat收购). 它对于学习UN ...
- iOS版 hello,world版本2
// // main.m // Hello // // Created by lishujun on 14-8-28. // Copyright (c) 2014年 lishujun. All rig ...
- 跨平台的WatiForSingleObject实现
移植win32程序时,有一个难点就是涉及到内核对象的操作,需要模拟win32的实现. 其中比较奇葩的一个是WaitForSingleObject系列. Linux中没有类似的timeout实现,模拟这 ...
- LightOj_1342 Aladdin and the Magical Sticks
题目链接 题意: 地上有n种棍子, 其中有两种类型, 一种类型是可识别, 一种类型是不可识别, 每个棍子都有一个权值. 当你捡到可识别的, 那么你以后就不会再捡这个棍子, 如果是不可识别的, 那么你有 ...
- C#事件(Event)学习日记
event 关键字的来由,为了简化自定义方法的构建来为委托调用列表增加和删除方法. 在编译器处理 event 关键字的时候,它会自动提供注册和注销方法以及任何必要的委托类型成员变量. 这些委托成员变量 ...
- 在ios7真机上和iOS6模拟器上运行是好的,而在iOS6真机上运行却报错
在ios7真机上和iOS6模拟器上运行是好的,而在iOS6真机上运行却报错 解决方法: 或是都设置为yes.. Build Active Architecture Only的意思是只生成适应的指令集
- 【itext】7步制作兼容各种文档格式的Itext5页眉页脚 实现page x pf y
itext5页眉页脚工具类,实现page x of y 完美兼容各种格式大小文档A4/B5/B3,兼容各种文档格式自动计算页脚XY轴坐标 鉴于没人做的这么细致,自己就写了一个itext5页眉页脚工具类 ...
- 使用javascript获取网址的各个参数
有时也挺无奈的,为了实现一个功能,不得不用到前台获取参数.幸亏,有javascript,不然真的是坑大发了,感谢javascript的创造者.开始show大图: 属性 值href:完整的 URL ...
- Git简明手册
文/AbnerKang(简书作者)原 文链接:http://www.jianshu.com/p/d7a7ba4f2341?utm_campaign=maleskine& utm_content ...
- logstash 安装WARNING: SSLSocket#session= is not supported
logstash官方提供的插件安装方法是: bin/plugin install logstash-output-webhdfs按照此方法,不出意料肯定会出现以下错误: [ec2-user@ip-xx ...