博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用AVCaptureSession捕捉视频
阅读量:5237 次
发布时间:2019-06-14

本文共 9053 字,大约阅读时间需要 30 分钟。

#import 
#import
#import
@interface ViewController : UIViewController
@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(0, 70, self.view.frame.size.width, self.view.frame.size.height-140);    [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:0];    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 == 0)    {        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:0] 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 *)captureOutputdidFinishRecordingToOutputFileAtURL:(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

 

转载于:https://www.cnblogs.com/fengmin/p/5525881.html

你可能感兴趣的文章
前端各种mate积累
查看>>
jQuery 1.7 发布了
查看>>
Python(软件目录结构规范)
查看>>
Windows多线程入门のCreateThread与_beginthreadex本质区别(转)
查看>>
Nginx配置文件(nginx.conf)配置详解1
查看>>
linux php编译安装
查看>>
name phone email正则表达式
查看>>
721. Accounts Merge
查看>>
「Unity」委托 将方法作为参数传递
查看>>
重置GNOME-TERMINAL
查看>>
redis哨兵集群、docker入门
查看>>
hihoCoder 1233 : Boxes(盒子)
查看>>
oracle中anyData数据类型的使用实例
查看>>
C++对vector里面的元素排序及取任意重叠区间
查看>>
软件测试——性能测试总结
查看>>
12.4站立会议
查看>>
Java Concurrentmodificationexception异常原因和解决方法
查看>>
客户端访问浏览器的流程
查看>>
codeforces水题100道 第二十二题 Codeforces Beta Round #89 (Div. 2) A. String Task (strings)
查看>>
c++||template
查看>>