iOS实现简单的录像功能

由于新项目需要用到录像功能,在网上找了点资料,自己做个了功能非常简单的demo,记录下来,方便以后使用。

```

#import"ViewController.h"

#import AVFoundation/AVFoundation.h

#import  MobileCoreServices/MobileCoreServices.h

@interfaceViewController()

@property(nonatomic,strong)UIImagePickerController* pickerController;

@property(nonatomic,strong)AVPlayer* player;

@property(nonatomic,strong)UIImageView* showImageView;

@end

@implementationViewController

- (void)viewDidLoad {

[superviewDidLoad];

UIButton*btn = [UIButtonbuttonWithType:UIButtonTypeSystem];

[btnsetTitle:@"开始录制"forState:UIControlStateNormal];

[btnsetTitleColor:[UIColorredColor]forState:UIControlStateNormal];

btn.frame=CGRectMake(100,100,100,50);

[self.viewaddSubview:btn];

[btnaddTarget:selfaction:@selector(btnClick:)forControlEvents:UIControlEventTouchUpInside];

self.showImageView= [[UIImageViewalloc]init];

self.showImageView.frame=CGRectMake(100,250,100,100);

[self.viewaddSubview:self.showImageView];

}

- (void)btnClick: (UIButton*)btn {

UIImagePickerController*vc = [[UIImagePickerControlleralloc]init];

vc.sourceType=UIImagePickerControllerSourceTypeCamera;

vc.cameraDevice=UIImagePickerControllerCameraDeviceRear;

vc.mediaTypes=@[(NSString*)kUTTypeMovie];

vc.videoQuality=UIImagePickerControllerQualityTypeIFrame1280x720;

vc.cameraCaptureMode=UIImagePickerControllerCameraCaptureModeVideo;

vc.allowsEditing=YES;// 允许编辑

[selfpresentViewController:vcanimated:YEScompletion:nil];

}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

NSString* mediaType = [infoobjectForKey:UIImagePickerControllerMediaType];

if([mediaTypeisEqualToString:(NSString*)kUTTypeMovie]) {

NSURL* url = [infoobjectForKey:UIImagePickerControllerMediaURL];

NSString* urlStr = [urlpath];

if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {

//保存视频到相簿

UISaveVideoAtPathToSavedPhotosAlbum(urlStr,self,@selector(video:didFinishSavingWithError:contextInfo:),nil);

}

}

[pickerdismissViewControllerAnimated:YEScompletion:nil];

}

- (void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{

if(error) {

NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);

}else{

NSLog(@"视频保存成功");

UIImage*img = [selfgetImage:videoPath];

self.showImageView.image= img;

}

}

#pragma mark - 将视频预览图通过视频URL取出来

- (UIImage*)getImage:(NSString*)videoURL{

AVURLAsset*asset = [[AVURLAssetalloc]initWithURL:[NSURLfileURLWithPath:videoURL]options:nil];

AVAssetImageGenerator*gen = [[AVAssetImageGeneratoralloc]initWithAsset:asset];

gen.appliesPreferredTrackTransform=YES;

CMTimetime =CMTimeMakeWithSeconds(0.0,600);

NSError*error =nil;

CMTimeactualTime;

CGImageRefimage = [gencopyCGImageAtTime:timeactualTime:&actualTimeerror:&error];

UIImage*thumb = [[UIImagealloc]initWithCGImage:image];

CGImageRelease(image);

returnthumb;

}

@end

```

后续会根据需求的不同来改进这个demo。

你可能感兴趣的:(iOS实现简单的录像功能)