使用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图 ...
随机推荐
- MATLAB r2014a 下载+安装+激活
MATLAB r2014a,下载包就有7个多GB,装完占用9个多GB,慎装.界面还不错,稍有改良. 其实本文是下载+安装+破解啦.读书人的事,怎么能叫破解呢?所以我这里讲的是如何激活啦. MATLAB ...
- css3百叶窗轮播图效果
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- CSS样式的优先级
1.相同权值情况下,CSS样式的优先级总结来说,就是--就近原则(离被设置元素越近优先级别越高): 内联样式表(标签内部)> 嵌入样式表(当前文件中)> 外部样式表(外部文件中). 2.权 ...
- babun,windows shell
babun是windows上的一个第三方shell,在这个shell上面你可以使用几乎所有linux,unix上面的命令,他几乎可以取代windows的shell. babun的几个特点: 使用bab ...
- 重启iis线程池和iis站点
服务器监控. 一定时间内或者iis异常,就重启线程池和站点 一般重启站点没啥用.. 重启线程池 效果明显. 重启站点: /// <summary> /// 根据名字重启站点.(没重启线程池 ...
- Contest20140906 ProblemC 菲波拉契数制 DP
C.菲波拉契数制时间:2s 内存:65536KB我们定义如下数列为菲波拉契数列: F (1) = 1 F (2) = 2 ...
- Android UI基础教程 目录
从csdn下载了这本英文版的书之后,又去京东搞了一个中文目录下来.对照着看. 话说,这本书绝对超值.有money的童鞋看完英文版记得去买中文版的~~ Android UI基础教程完整英文版 pdf+源 ...
- 监控 DNS 流量,预防安全隐患五大招!
尽管 IT 管理员尽心尽责地监控设备.主机和网络是否存在恶意活动的迹象,却往往出力不讨好.主机入侵检测和端点保护对很多公司来说可能是"必需"的安全措施,但如果要找出 RAT.roo ...
- apple ID的重要性
当手机丢失时,您可以将对应的产品码提供给运营商,提高找回丢失手机的可能性. 2.去App store下载“查找我的iPhone(Find My iPhone)”,立刻安上,用你的app ...
- Linux 查看磁盘分区、文件系统、使用情况的命令和相关工具介绍
磁盘分区表.文件系统的查看.统计的工具很多,有些工具是多功能的,不仅仅是查看磁盘的分区表,而且也能进行磁盘分区的操作:但在本文,我们只讲磁盘分区的查看,以及分区的使用情况的查看:本文只是给新手上路之用 ...