-
使用原生相機(jī) UIImagePickerController 來(lái)錄制
一刻诊、準(zhǔn)備
1.添加依賴庫(kù)AVFoundation.framework
2.導(dǎo)入頭文件
<AVFoundation/AVFoundation.h>#import <MobileCoreServices/MobileCoreServices.h>
3.添加成員變量:
{
//視頻錄制
UIImagePickerController *_picker;
//拍攝視頻資源控制符
NSURL *_movieUrl;
//保存到本地資源控制符
NSURL *_locoaUrl;
//視頻播放
AVPlayer *player;
}
4.設(shè)置權(quán)限
麥克風(fēng)權(quán)限:Privacy - Microphone Usage Description 是否允許此App使用你的麥克風(fēng)
相機(jī)權(quán)限: Privacy - Camera Usage Description 是否允許此App使用你的相機(jī)?
相冊(cè)權(quán)限: Privacy - Photo Library Usage Description 是否允許此App訪問(wèn)你的媒體資料庫(kù)洛勉?
通訊錄權(quán)限:
Privacy - Contacts Usage Description 是否允許此App訪問(wèn)你的通訊錄邻邮?
藍(lán)牙權(quán)限:Privacy - Bluetooth Peripheral Usage Description 是否許允此App使用藍(lán)牙?
語(yǔ)音轉(zhuǎn)文字權(quán)限:Privacy - Speech Recognition Usage Description 是否允許此App使用語(yǔ)音識(shí)別?
日歷權(quán)限:Privacy - Calendars Usage Description 是否允許此App使用日歷征绎?
定位權(quán)限:Privacy - Location When In Use Usage Description 我們需要通過(guò)您的地理位置信息獲取您周邊的相關(guān)數(shù)據(jù)
后臺(tái)定位權(quán)限: Privacy - Location Always Usage Description 我們需要通過(guò)您的地理位置信息獲取您周邊的相關(guān)數(shù)據(jù)定位的需要這么寫,防止上架被拒磨取。
二人柿、代碼:
/**
**
****點(diǎn)擊按鈕開始錄制
** @param sender <#sender description#> */
- (IBAction)startPicker:(id)sender {
//初始化 UIImagePickerController
_picker = [[UIImagePickerController alloc]init];
_picker.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//來(lái)源為攝像頭
_picker.sourceType = UIImagePickerControllerSourceTypeCamera;
// 重點(diǎn) 是設(shè)置媒體類型為視頻 電影 類型為數(shù)組
_picker.mediaTypes = @[(NSString*)kUTTypeMovie];
//設(shè)置為錄制模式
_picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
//下面為默認(rèn)設(shè)置
//錄制時(shí)間
_picker.videoMaximumDuration = 10;
//質(zhì)量
_picker.videoQuality = UIImagePickerControllerQualityTypeIFrame960x540;
//顯示攝像頭控制面板 設(shè)置為NO 使用cameraOverlayView 自定義界面
_picker.showsCameraControls = YES;
// picker.cameraOverlayView 攝像頭上覆蓋的視圖,可用通過(guò)這個(gè)視頻來(lái)自定義拍照或錄像界面
//攝像頭 前置/后置
_picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
//閃光燈模式 自動(dòng)
_picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
}
[self presentViewController:_picker animated:YES completion:nil];
}
#pragma mark UIImagePickerControllerDelegate 代理方法(在代理方法中處理視頻)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
[picker dismissViewControllerAnimated:YES completion:nil];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:@"public.image"]) {
//如果媒體類型為圖片
//相機(jī):裁剪后的圖片//
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
//原始圖片
UIImage *image2 = [info objectForKey:UIImagePickerControllerOriginalImage];
}else if (
[mediaType isEqualToString:@"public.movie"]){//如果媒體類型為視頻
_movieUrl = [info objectForKey:UIImagePickerControllerMediaURL];
//獲取視頻資源定位
//將視頻保存到本地
NSData *fileData = [NSData dataWithContentsOfURL:_movieUrl];
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
path = [path stringByAppendingPathComponent:@"save.mp4"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isSuccess = [fileManager createFileAtPath:path contents:fileData attributes:nil];
if (isSuccess) {
NSLog(@"保存到本地成功");
//保存本地資源定位
_locoaUrl = [NSURL URLWithString:path];
} else {
NSLog(@"保存到本地失敗");
} }
NSLog(@"拍照忙厌,相片完成”);
//將視頻保存到相冊(cè)
UISaveVideoAtPathToSavedPhotosAlbum([_movieUrl path], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);}
/* 實(shí)現(xiàn)錄制過(guò)程中點(diǎn)擊取消退出 @param picker <#picker description#> */
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
}
/** 視頻格式轉(zhuǎn)換(帶轉(zhuǎn)換功能額)
** @param sender <#sender description#> */
- (IBAction)formatConverter:(id)sender{
//轉(zhuǎn)換時(shí)文件不能已存在凫岖,否則出錯(cuò)
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:_movieUrl options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
//判斷是否包含該質(zhì)量的視頻
if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
//用時(shí)間給文件全名,以免重復(fù)逢净,在測(cè)試的時(shí)候其實(shí)可以判斷文件是否存在若存在哥放,則刪除,重新生成文件即可
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
NSString *resultPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]];
exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
exportSession.outputFileType = AVFileTypeMPEG4;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
switch (exportSession.status) {
case AVAssetExportSessionStatusUnknown:
NSLog(@"AVAssetExportSessionStatusUnknown");
break;
case AVAssetExportSessionStatusWaiting:
NSLog(@"AVAssetExportSessionStatusWaiting");
break;
case AVAssetExportSessionStatusExporting:
NSLog(@"AVAssetExportSessionStatusExporting");
break;
case AVAssetExportSessionStatusCompleted:
NSLog(@"AVAssetExportSessionStatusCompleted");
{
NSURL *fileUrl = [NSURL URLWithString:resultPath];
NSLog(@"轉(zhuǎn)換結(jié)束");
[self fileSizeAtPath:fileUrl]; _endUrl = fileUrl;
}
break;
case AVAssetExportSessionStatusFailed:
NSLog(@"AVAssetExportSessionStatusFailed");
break;
}
}];
}
}
三爹土、其他:
/** **計(jì)算文件大小** @param filePathUrl <#filePathUrl description#> @return 返回單位為Byte */
- (unsigned long long)fileSizeAtPath:(NSURL *)filePathUrl{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isExist = [fileManager fileExistsAtPath:[filePathUrl path]];
if (isExist){
unsigned long long fileSize = [[fileManager attributesOfItemAtPath:[filePathUrl path] error:nil] fileSize];
NSLog(@"%@大小: %f M",[filePathUrl path],fileSize/1024.0/1024.0);
return fileSize;
} else {
NSLog(@"file is not exist");
return 0;
}
}
/** **點(diǎn)擊播放本地視頻** @param sender <#sender description#> */
- (IBAction)playLocalMove:(id)sender {
NSURL *movieUrl = [NSURL fileURLWithPath:[_locoaUrl path]];
//直接調(diào)用_localUrl無(wú)法播放甥雕,不知道為什么
player = [AVPlayer playerWithURL:movieUrl];
//3、創(chuàng)建視頻顯示的圖層
AVPlayerLayer *showVodioLayer = [AVPlayerLayer playerLayerWithPlayer:player];
showVodioLayer.frame = self.view.frame;
[self.view.layer addSublayer:showVodioLayer];
//4着饥、播放視頻
[player play];
}
/** **獲取相冊(cè)內(nèi)視頻的時(shí)長(zhǎng)** @param URL <#URL description#> @return <#return value description#> */
-(CGFloat)getVideoLength:(NSURL*)URL{
NSDictionary*opts=[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *urlAs = [AVURLAsset URLAssetWithURL:URL options:opts];
CGFloat second= urlAs.duration.value/urlAs.duration.timescale;
return second;
}
//**視頻保存后的回調(diào)**
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error) {
NSLog(@"保存視頻過(guò)程中發(fā)生錯(cuò)誤犀农,錯(cuò)誤信息:%@",error.localizedDescription);
}else{
NSLog(@"視頻保存成功.");
}
}
視頻質(zhì)量與大小的關(guān)系(以10s為例)
// UIImagePickerControllerQualityTypeHigh = 0, 高,18M
// UIImagePickerControllerQualityTypeMedium = 1 , 中等宰掉,0.95M
// UIImagePickerControllerQualityTypeLow = 2, 低呵哨,0.19M
// UIImagePickerControllerQualityType640x480 , 3.745M
// UIImagePickerControllerQualityTypeIFrame1280x720赁濒, 50M
// UIImagePickerControllerQualityTypeIFrame960x540, 35M
四孟害、UIImagePickerController常用屬性拒炎、方法
1.+(BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType;
// 檢查指定源是否在設(shè)備上可用。
// 檢查照片源是否可用
[UIImagePickerControlle isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]
2.allowsEditing
默認(rèn)NO,是否允許編輯允許編輯.
[imagePicker setAllowsEditing:YES];
3. videoMaximumDuration
設(shè)置UIImagePicker的最大視頻持續(xù)時(shí)間.默認(rèn)10分鐘
4. availableMediaTypesForSourceType:
//指定源可用的媒體種類
//獲得相機(jī)模式下支持的媒體類型
NSArray* availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
5. sourceType
設(shè)置UIImagePicker照片源類型挨务,默認(rèn)有3種击你。
照片源類型 UIImagePickerControllerSourceTypeCamera
照相機(jī) UIImagePickerControllerSourceTypePhotoLibrary
照片庫(kù)(通過(guò)同步存放的,用戶不能刪除) UIImagePickerControllerSourceTypeSavedPhotosAlbum
保存的照片(通過(guò)拍照或者截屏保存的谎柄,用戶可以刪除)