iOS視頻錄制(或選擇)壓縮及上傳功能(整理)
最新做的一個(gè)功能涉及到了視頻的錄制、壓縮及上傳。根據(jù)網(wǎng)上諸多大神的經(jīng)驗(yàn),終于算是調(diào)通了,但也發(fā)現(xiàn)了一些問(wèn)題,所以把我的經(jīng)驗(yàn)分享一下。
首先,肯定是調(diào)用一下系統(tǒng)的相機(jī)或相冊(cè)
代碼很基本:
//選擇本地視頻
- (void)choosevideo
{
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三種分別是camera,photoLibrary和photoAlbum
NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有兩個(gè)分別是@"public.image",@"public.movie"
ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//設(shè)置媒體類(lèi)型為public.movie
[self presentViewController:ipc animated:YES completion:nil];
ipc.delegate = self;//設(shè)置委托
}
//錄制視頻
- (void)startvideo
{
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三種分別是camera,photoLibrary和photoAlbum
NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有兩個(gè)分別是@"public.image",@"public.movie"
ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//設(shè)置媒體類(lèi)型為public.movie
[self presentViewController:ipc animated:YES completion:nil];
ipc.videoMaximumDuration = 30.0f;//30秒
ipc.delegate = self;//設(shè)置委托
}
iOS錄制的視頻格式是mov的,在Android和Pc上都不太好支持,所以要轉(zhuǎn)換為MP4格式的,而且壓縮一下,畢竟我們上傳的都是小視頻,不用特別清楚
為了反饋的清楚,先放兩個(gè)小代碼來(lái)獲取視頻的時(shí)長(zhǎng)和大小,也是在網(wǎng)上找的,稍微改了一下。
- (CGFloat) getFileSize:(NSString *)path
{
NSLog(@"%@",path);
NSFileManager *fileManager = [NSFileManager defaultManager];
float filesize = -1.0;
if ([fileManager fileExistsAtPath:path]) {
NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//獲取文件的屬性
unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
filesize = 1.0*size/1024;
}else{
NSLog(@"找不到文件");
}
return filesize;
}//此方法可以獲取文件的大小,返回的是單位是KB。
- (CGFloat) getVideoLength:(NSURL *)URL
{
AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
CMTime time = [avUrl duration];
int second = ceil(time.value/time.timescale);
return second;
}//此方法可以獲取視頻文件的時(shí)長(zhǎng)。
接收并壓縮
//完成視頻錄制,并壓縮后顯示大小、時(shí)長(zhǎng)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]);
NSURL *newVideoUrl ; //一般.mp4
NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用時(shí)間給文件全名,以免重復(fù),在測(cè)試的時(shí)候其實(shí)可以判斷文件是否存在若存在,則刪除,重新生成文件即可
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//這個(gè)是保存在app自己的沙盒路徑里,后面可以選擇是否在上傳后刪除掉。我建議刪除掉,免得占空間。
[picker dismissViewControllerAnimated:YES completion:nil];
[self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}
- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
completeHandler:(void (^)(AVAssetExportSession*))handler
{
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
// NSLog(resultPath);
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse= YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void)
{
switch (exportSession.status) {
case AVAssetExportSessionStatusCancelled:
NSLog(@"AVAssetExportSessionStatusCancelled");
break;
case AVAssetExportSessionStatusUnknown:
NSLog(@"AVAssetExportSessionStatusUnknown");
break;
case AVAssetExportSessionStatusWaiting:
NSLog(@"AVAssetExportSessionStatusWaiting");
break;
case AVAssetExportSessionStatusExporting:
NSLog(@"AVAssetExportSessionStatusExporting");
break;
case AVAssetExportSessionStatusCompleted:
NSLog(@"AVAssetExportSessionStatusCompleted");
NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
//UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//這個(gè)是保存到手機(jī)相冊(cè)
[self alertUploadVideo:outputURL];
break;
case AVAssetExportSessionStatusFailed:
NSLog(@"AVAssetExportSessionStatusFailed");
break;
}
}];
}
我這里用了一個(gè)提醒,因?yàn)槲业姆?wù)器比較弱,不能傳太大的文件
-(void)alertUploadVideo:(NSURL*)URL{
CGFloat size = [self getFileSize:[URL path]];
NSString *message;
NSString *sizeString;
CGFloat sizemb= size/1024;
if(size<=1024){
sizeString = [NSString stringWithFormat:@"%.2fKB",size];
}else{
sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];
}
if(sizemb<2){
[self uploadVideo:URL];
}
else if(sizemb<=5){
message = [NSString stringWithFormat:@"視頻%@,大于2MB會(huì)有點(diǎn)慢,確定上傳嗎?", sizeString];
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
message: message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
[[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就刪除,以免占用手機(jī)硬盤(pán)空間(沙盒)
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self uploadVideo:URL];
}]];
[self presentViewController:alertController animated:YES completion:nil];
}else if(sizemb>5){
message = [NSString stringWithFormat:@"視頻%@,超過(guò)5MB,不能上傳,抱歉。", sizeString];
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
message: message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
[[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就刪除,以免占用手機(jī)硬盤(pán)空間
}]];
[self presentViewController:alertController animated:YES completion:nil];
}
}
最后上上傳的代碼,這個(gè)是根據(jù)服務(wù)器來(lái)的,而且還是用的MKNetworking,據(jù)說(shuō)已經(jīng)過(guò)時(shí)了,放上來(lái)大家參考一下吧,AFNet也差不多,就是把NSData傳上去。
-(void)uploadVideo:(NSURL*)URL{
//[MyTools showTipsWithNoDisappear:nil message:@"正在上傳..."];
NSData *data = [NSData dataWithContentsOfURL:URL];
MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"www.ylhuakai.com" customHeaderFields:nil];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSString *updateURL;
updateURL = @"/alflower/Data/sendupdate";
[dic setValue:[NSString stringWithFormat:@"%@",User_id] forKey:@"openid"];
[dic setValue:[NSString stringWithFormat:@"%@",[self.web objectForKey:@"web_id"]] forKey:@"web_id"];
[dic setValue:[NSString stringWithFormat:@"%i",insertnumber] forKey:@"number"];
[dic setValue:[NSString stringWithFormat:@"%i",insertType] forKey:@"type"];
MKNetworkOperation *op = [engine operationWithPath:updateURL params:dic httpMethod:@"POST"];
[op addData:data forKey:@"video" mimeType:@"video/mpeg" fileName:@"aa.mp4"];
[op addCompletionHandler:^(MKNetworkOperation *operation) {
NSLog(@"[operation responseData]-->>%@", [operation responseString]);
NSData *data = [operation responseData];
NSDictionary *resweiboDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSString *status = [[resweiboDict objectForKey:@"status"]stringValue];
NSLog(@"addfriendlist status is %@", status);
NSString *info = [resweiboDict objectForKey:@"info"];
NSLog(@"addfriendlist info is %@", info);
// [MyTools showTipsWithView:nil message:info];
// [SVProgressHUD showErrorWithStatus:info];
if ([status isEqualToString:@"1"])
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
[[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//上傳之后就刪除,以免占用手機(jī)硬盤(pán)空間;
}else
{
//[SVProgressHUD showErrorWithStatus:dic[@"info"]];
}
// [[NSNotificationCenter defaultCenter] postNotificationName:@"StoryData" object:nil userInfo:nil];
}errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
}];
[engine enqueueOperation:op];
}
以上所述是小編給大家介紹的iOS視頻錄制(或選擇)壓縮及上傳功能(整理),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- iOS開(kāi)發(fā)之獲取系統(tǒng)相冊(cè)中的圖片與視頻教程(內(nèi)帶url轉(zhuǎn)換)
- IOS實(shí)現(xiàn)視頻動(dòng)畫(huà)效果的啟動(dòng)圖
- 淺析iOS中視頻播放的幾種方案
- iOS實(shí)現(xiàn)視頻和圖片的上傳思路
- iOS仿微信相機(jī)拍照、視頻錄制功能
- 詳解iOS應(yīng)用中播放本地視頻以及選取本地音頻的組件用法
- iOS中視頻播放器的簡(jiǎn)單封裝詳解
- iOS中讀取照片庫(kù)及保存圖片或視頻到照片庫(kù)的要點(diǎn)解析
- iOS 本地視頻和網(wǎng)絡(luò)視頻流播放實(shí)例代碼
- iOS視頻中斷后臺(tái)音樂(lè)播放的處理方法
相關(guān)文章
iOS應(yīng)用腳本重簽名的實(shí)現(xiàn)方法
這篇文章主要介紹了iOS應(yīng)用腳本重簽名的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
iOS開(kāi)發(fā)刪除storyboard步驟詳解
這篇文章主要為大家介紹了iOS系列學(xué)習(xí)之刪除storyboard步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
iOS實(shí)現(xiàn)支付寶螞蟻森林隨機(jī)按鈕及抖動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了iOS實(shí)現(xiàn)支付寶螞蟻森林隨機(jī)按鈕及抖動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
iOS TabBarItem設(shè)置紅點(diǎn)(未讀消息)
本文主要介紹了iOS利用TabBarItem設(shè)置紅點(diǎn)(未讀消息)的相關(guān)知識(shí)。具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧2017-04-04
IOS提醒用戶(hù)重新授權(quán)打開(kāi)定位功能
這篇文章主要介紹了IOS提醒用戶(hù)重新授權(quán)打開(kāi)定位功能的相關(guān)資料,需要的朋友可以參考下2015-12-12
IOS 上架后出現(xiàn)90034代碼錯(cuò)誤問(wèn)題解決
這篇文章主要介紹了IOS 上架后出現(xiàn)90034代碼錯(cuò)誤問(wèn)題解決的相關(guān)資料,需要的朋友可以參考下2016-11-11

