iOS 视频录制
2016-03-22 本文已影响241人
小辉辉___
#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePick;
@property (nonatomic, assign) int isVideo;
@property (nonatomic, weak) IBOutlet UIImageView *photo;
@property (nonatomic, strong) AVPlayer *player;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_isVideo = YES;//是否是录制视频
}
- (IBAction)takeClick:(id)sender {
[self presentViewController:self.imagePick animated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果是拍照
UIImage *image;
if (self.imagePick.allowsEditing) {
image = [info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
}else{
image = [info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
}
[self.photo setImage:image];//显示照片
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//保存到相册
}else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
NSString *urlStr = [url path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}
}
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 私有方法
-(UIImagePickerController *)imagePick{
if (_imagePick == nil) {
_imagePick = [[UIImagePickerController alloc]init];
_imagePick.sourceType = UIImagePickerControllerSourceTypeCamera;//设置image picker的来源
_imagePick.cameraDevice = UIImagePickerControllerCameraDeviceFront;//设置摄像头类型
if (self.isVideo) {
_imagePick.mediaTypes = @[(NSString *)kUTTypeMovie];
_imagePick.videoQuality = UIImagePickerControllerQualityTypeIFrame1280x720;
_imagePick.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;//设置摄像头模式
}else{
_imagePick.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
}
_imagePick.allowsEditing = YES;//允许编辑
_imagePick.delegate = self;//设置代理
}
return _imagePick;
}
//视屏保存后的回调
-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error) {
NSLog(@"发生错误");
}else{
NSURL *url = [NSURL fileURLWithPath:videoPath];
_player = [AVPlayer playerWithURL:url];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
playerLayer.frame = self.photo.frame;
[self.photo.layer addSublayer:playerLayer];
[_player play];
}
}
@end
测试截图.jpg