#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捕捉视频的更多相关文章

  1. selenium捕捉视频

    捕捉视频 有时候我们未必能够分析故障只需用日志文件或截图的帮助.有时捕获完整的执行视频帮助.让我们了解如何捕捉视频. 我们将利用Monte媒体库的执行相同. 配置 第1步:导航到URL - http: ...

  2. CSS canvas 捕捉视频video元素截图

    video元素介绍: http://www.runoob.com/html/html5-video.html https://developer.mozilla.org/zh-CN/docs/Web/ ...

  3. AVCaptureSession音频视频采集

    // // AudioVideoCaptureViewController.m // live // // Created by lujunjie on 2016/10/31. // Copyrigh ...

  4. iOS AVCaptureSession 小视频开发总结,支持设备旋转

    iOS开发中当我们想要自定义相机拍照或摄像界面时,UIImagePickerController无法满足我们的需求,这时候我们可以使用AVFoundation.framework这个framework ...

  5. 使用AVCaptureSession捕捉静态图片

    #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <AssetsLibrary/ ...

  6. 如何在视频处理控件TVideoGrabber中设置音频捕捉设备

    TVideoGrabber不仅可以捕捉视频,还可以作为多媒体播放器,并支持包括C#..NET.VB.NET.C++.Delphi.C++Builder和ActiveX平台,本文将剖析TVideoGra ...

  7. 视频捕捉全教程(vc+vfw)

    目 录 一. 视频捕获快速入门 二.基本的捕获设置 1.设置捕获速度: 2.设置终止捕获 3.捕获的时间限制 三.关于捕获窗口 1.创建一个AVICAP捕获窗口 2.将一个捕获窗口连接至捕获设备 3. ...

  8. VirtualDub - 开源视频捕捉及线性处理软件

    VirtualDub是一个开放源代码的视频捕捉及线性处理软件.它由Avery Lee编写,遵循GPL协议.VirtualDub可以通过摄像头捕捉视频. 官方网站http://virtualdub.or ...

  9. Direcshow中视频捕捉和参数设置报告

    Direcshow中视频捕捉和参数设置报告 1.      关于视频捕捉(About Video Capture in Dshow) 1视频捕捉Graph的构建 一个能够捕捉音频或者视频的graph图 ...

随机推荐

  1. (C语言)char类型与int类型相加

    #include <stdio.h> int main(void) { ; ; int c = a + b; a += b; printf("c=%d",c); //p ...

  2. 练习2 J题 - 多项式求和

      Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u   Description 多项式 ...

  3. Android 开发遇到的问题及解决办法

    Failed to resolve: com.android.support:appcompat-v7:23.4.0 问题解决办法: 1.在Android SDK Manager中找到对应的SDK版本 ...

  4. webform的三级联动

    webform的三级联动 与winform一样,只不过需把DropDownList的AutoPostBack属性改为True. *简单日期的编写方法:用是三个DropDownList分别代表年月日,用 ...

  5. 【关于JavaScript】常见表单用户名、密码不能为空

    在论坛等系统的用户注册功能中,如果用户忘记填写必填信息,如用户名.密码等,浏览器会弹出警告框,提示用户当前有未填信息. 这个典型的应用就是通过JavaScript实现的.如图所示是一个简单的用户注册页 ...

  6. 跨终端Web之Hybrid App

    Native App(以下简称Native)和Mobile Web(以下简称Web)二者混合开发的产物被称为Hybrid App(以下简称Hybrid).Hybrid并不是什么新概念,最早可以追溯到S ...

  7. 【JavsScript】XMLHttpRequest2的进步之处

    本文参考自:XMLHttpRequest2 新技巧 (重点保留demo,方便自己日后查阅) HTML5是现在web开发中的热点,虽然关于web app和local app一直有争论,但是从技术学习的角 ...

  8. 【Java】Java Platform

    The Java platform has two components: The Java Virtual Machine The Java Application Programming Inte ...

  9. java中基本类型封装对象所占内存的大小(转)

    这是一个程序,java中没有现成的sizeof的实现,原因主要是java中的基本数据类型的大小都是固定的,所以看上去没有必要用sizeof这个关键字. 实现的想法是这样的:java.lang.Runt ...

  10. apk,task,android:process与android:sharedUserId的区别

    apk一般占一个dalvik,一个进程,一个task.通过设置也可以多个进程,占多个task. task是一个activity的栈,其中"可能"含有来自多个App的activity ...