使用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图 ...
随机推荐
- 转:阿里开源Mysql分布式中间件:Cobar
原文来自于:http://hualong.iteye.com/blog/2102798 这几天研究了下Cobar, Cobar是阿里巴巴研发的关系型数据的分布式处理系统(Amoeba的升级版,该产品成 ...
- 防止 DDoS 攻击的五个「大招」!
提到 DDoS 攻击,很多人不会陌生.上周,美国当地时间 12 月 29 日,专用虚拟服务器提供商 Linode 遭到 DDoS 攻击,直接影响其 Web 服务器的访问,其中 API 调用和管理功能受 ...
- HttpClient 教程
前言 超文本传输协议(HTTP)也许是当今互联网上使用的最重要的协议了.Web服务,有网络功能的设备和网络计算的发展,都持续扩展了HTTP协议的角色,超越了用户使用的Web浏览器范畴,同时,也增加了需 ...
- bzoj2729
一看就知道是数学题,考虑插空法由于老师只有两人,所以先对老师进行插空这里考虑两种情况:1.两个老师站在同一处,即两个男生之间站了两个老师这时候需要一个女生站在两个老师之间,再对女生插空,根据乘法原理即 ...
- BZOJ1603: [Usaco2008 Oct]打谷机
1603: [Usaco2008 Oct]打谷机 Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 602 Solved: 458[Submit][Stat ...
- VI 命令学习指南
ctrl+b 屏幕向后(上)移动一屏 ctrl+f 屏幕向前(下)移动一屏 ctrl+u 屏幕向后(上)移动半屏 ctrl+d 屏幕向前(下)移动半屏
- JS原型函数相关基础知识
函数对象和普通对象 //普通对象 var oo1 = {}, oo2 = new Object(), oo3 = []; console.log(typeof oo1 + ',' + typeof o ...
- autoit使用
autoit下载地址: http://www.autoitx.com/thread-12964-1-1.html?sid=4zMMSb 在autoit的安装目录下有个Au3Info.exe文件,该文件 ...
- Matlab与CCS的连接
1.CCS概述 Matlab 6.5(R13)或以上集成了CCSLink工具,可以支持CCS能够识别的任何板卡及其硬件DSP. 验证CCSLink是否在主机上安装成功,Matlab输入命令:help ...
- Java同步
同步:★★★★★ 好处:解决了线程安全问题. 弊端:相对降低性能,因为判断锁需要消耗资源,产生了死锁. 定义同步是有前提的: 1,必须要有两个或者两个以上的线程,才需要同步. 2,多个线程必须保证使用 ...