Capturing video using Avcapturesession

Source: Internet
Author: User

#import<UIKit/UIKit.h>#import<AVFoundation/AVFoundation.h>#import<AssetsLibrary/AssetsLibrary.h>@interfaceViewcontroller: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"@interfaceViewcontroller ()@end@implementationViewcontroller@synthesizeCapturebutton;@synthesizeModecontrol;- (void) viewdidload{[Super Viewdidload]; //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, AVVIDEOC    Odeckey, 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, -, Self.view.frame.size.width, self.view.frame.size.height- $); [Aview.layer Addsublayer:previewlayer];}- (void) didreceivememorywarning{[Super didreceivememorywarning]; //Dispose of any resources the can be recreated.}-(BOOL) shouldautorotatetointerfaceorientation: (uiinterfaceorientation) interfaceorientation{return(Interfaceorientation! =uiinterfaceorientationportraitupsidedown);}- (void) capturestillimage{avcaptureconnection*stillimageconnection = [Self.stillImageOutput.connections objectatindex:0]; if([stillimageconnection isvideoorientationsupported]) [Stillimageconnection Setvideoorientation:avcapturevideo        Orientationportrait];                                                         [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: (alassetorientatio n) [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 a saved to photos library"                                                        Delegate: nil Cancelbuttontitle:@"OK"Otherbuttontitles:nil, nil];              } [alert show];         }              ]; }         ElseNSLog (@"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]; }    returnOutputurl;}-(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 portraitNsarray *array = [[Self.captureSession.outputs objectatindex:0] connections];  for(Avcaptureconnection *connectioninchArray) {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 is successful.        IDValue =[[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 is not a saved to you photos library"                                                   Delegate: nil Cancelbuttontitle:@"OK"Otherbuttontitles:nil, nil];         } [alert show];    }         ]; }}@end

Capturing video using Avcapturesession

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.