#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
AVPlayerViewControllerDelegate
{
AVPlayerViewController *mPMoviePlayerViewController;
}
//調用系統詳解
UIImagePickerController *pickerCon = [[UIImagePickerController alloc]init];
pickerCon.sourceType = UIImagePickerControllerSourceTypeCamera;
pickerCon.mediaTypes = @[(NSString *)kUTTypeMovie];//設定相機爲視頻
pickerCon.cameraDevice = UIImagePickerControllerCameraDeviceRear;//設置相機後攝像頭
pickerCon.videoMaximumDuration = 10;//最長拍攝時間
pickerCon.videoQuality = UIImagePickerControllerQualityTypeIFrame960x540;//拍攝質量
pickerCon.allowsEditing = YES;//是否可編輯
pickerCon.delegate = self;
[self presentViewController:pickerCon animated:YES completion:nil];
//代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
//以下均是在使用攝像頭拍照情況下,在使用相冊或圖庫功能時大致相同
// 獲取媒體類型信息
NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
//如果是拍照
UIImage *image;
//如果允許編輯則獲得編輯後的照片,否則獲取原始照片
if (picker.allowsEditing) {
image=[info objectForKey:UIImagePickerControllerEditedImage];//獲取編輯後的照片
}else{
image=[info objectForKey:UIImagePickerControllerOriginalImage];
//獲取原始照片
}
/* CGRect cropRect = [[info objectForKey:UIImagePickerControllerCropRect] CGRectValue]; UIImage * cropImage=[info objectForKey:UIImagePickerControllerOriginalImage]; UIImage *rotatedOriginalImage = [cropImage imageRotatedByDegrees:90.0]; CGImageRef imageRef = CGImageCreateWithImageInRect(rotatedOriginalImage.CGImage, cropRect); UIImage * resultImage = [UIImage imageWithCGImage:imageRef]; //以此法獲得的圖片即爲編輯後的圖片其中-imageRotatedByDegrees: 方法是將圖片順時針轉動90度的方法 */
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image: didFinishSavingWithError: contextInfo:), nil);
// 若保存到相簿後沒有其他操作可以:UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeMovie]){//如果是錄製視頻
NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];//視頻路徑
NSString *urlStr=[url path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
//保存視頻到相簿,注意也可以使用ALAssetsLibrary來保存
UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);//保存視頻到相簿
////////000
_videoURL = url;
_collectionView.hidden = YES;
self.backgroundIV.hidden = NO;
self.playBtn.hidden = NO;
self.backgroundIV.image= [self getImage:[[_videoURL absoluteString ] stringByReplacingOccurrencesOfString:@"file://" withString:@""]];
aVideoUrlForPlay = [NSString stringWithFormat:@"%@", _videoURL];
NSLog(@"壓縮前視頻時長=%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:url]]);
NSLog(@"壓縮前視頻大小=%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[url path]]]);
NSURL *newVideoUrl ; //一般.mp4
NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用時間給文件全名,以免重複,在測試的時候其實可以判斷文件是否存在若存在,則刪除,重新生成文件即可
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//這個是保存在app自己的沙盒路徑裏,後面可以選擇是否在上傳後刪除掉。我建議刪除掉,免得佔空間。
[self convertVideoQuailtyWithInputURL:url outputURL:newVideoUrl completeHandler:nil];
// NSData *data = [NSData dataWithContentsOfFile:[url absoluteString]];
// NSData *data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@", [[_videoURL absoluteString ] stringByReplacingOccurrencesOfString:@"file://" withString:@""]]];
}
}
[picker dismissViewControllerAnimated:YES completion:^{ }];
}
//壓縮
- (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];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse= YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void){
switch (exportSession.status) {
case AVAssetExportSessionStatusCancelled:
break;
case AVAssetExportSessionStatusUnknown:
break;
case AVAssetExportSessionStatusWaiting:
break;
case AVAssetExportSessionStatusExporting:
break;
case AVAssetExportSessionStatusCompleted:
NSLog(@"壓縮後時長%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
NSLog(@"壓縮後大小%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//這個是保存到手機相冊
[self alertUploadVideo:outputURL];
break;
case AVAssetExportSessionStatusFailed:
break;
}
}];
}
//上傳提示
-(void)alertUploadVideo:(NSURL*)URL{
_videoURL = 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 changeUserVideoView:URL];
}else if(sizemb<=5){
message = [NSString stringWithFormat:@"視頻%@,大於2MB會有點慢,確定上傳嗎?", sizeString];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:message message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
[alertView show];
}else if(sizemb>5){
message = [NSString stringWithFormat:@"視頻%@,超過5MB,不能上傳,抱歉。", sizeString];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:message message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定", nil];
[alertView show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
[[NSFileManager defaultManager] removeItemAtPath:[_videoURL path] error:nil];//取消之後就刪除,以免佔用手機硬盤空間
}else{
[self changeUserVideoView:_videoURL];
}
}
//上傳視頻
- (void)changeUserVideoView:(NSURL *)url{
NSData *data = [NSData dataWithContentsOfURL:url];
// NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
self.navigationItem.rightBarButtonItem.enabled = YES;
NSMutableDictionary *viedoExparams = [[NSMutableDictionary alloc]init];
[viedoExparams addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:data,@"pic",nil]];
[CKHttpCommunicate createRequest:HTTP_upload2Tmp WithParam:nil withExParam:viedoExparams withMethod:POST success:^(id result) {
_selectedVideodWithImagrUrl = [NSString stringWithFormat:@"%@",result[@"d"]];
if (_selectedVideodWithImagrUrl != nil) {
[MBProgressHUD hideHUDForView:self.view animated:nil];
self.navigationItem.rightBarButtonItem.enabled = YES;
}
} uploadFileProgress:^(NSProgress *uploadProgress) {
} failure:^(NSError *erro) {
}];
}
- (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;
}//此方法可以獲取視頻文件的時長。
// 照片保存到相簿的回調
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存照片過程中發生錯誤,錯誤信息:%@",error.localizedDescription);
}else{
NSLog(@"照片保存成功.");
}
}
// 視頻保存到相簿的回調
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存視頻過程中發生錯誤,錯誤信息:%@",error.localizedDescription);
}else{
NSLog(@"視頻保存成功.");
//錄製完之後可以使用AVPlayer自動播放
NSURL *url=[NSURL fileURLWithPath:videoPath];
NSLog(@"視頻路徑=%@", url);
}
}
//上傳完畢後播放視頻方法
- (void)addPlayerView {
// EditVideoViewController* cor = [[EditVideoViewController alloc] init];
// cor.videoURL = _videoURL;
// cor.isyulan = @"1";
// [self pushViewController:cor animated:YES];
// 2、初始化媒體播放控制器
if (mPMoviePlayerViewController) {
mPMoviePlayerViewController = nil;
}
// 3、配置媒體播放控制器
mPMoviePlayerViewController = [[AVPlayerViewController alloc] init];
// 設置媒體源數據
mPMoviePlayerViewController.player = [AVPlayer playerWithURL:_videoURL];
// 設置拉伸模式
mPMoviePlayerViewController.videoGravity = AVLayerVideoGravityResizeAspect;
// 設置是否顯示媒體播放組件
mPMoviePlayerViewController.showsPlaybackControls = YES;
// 設置代理
mPMoviePlayerViewController.delegate = self;
// 播放視頻
[mPMoviePlayerViewController.player play];
// 設置媒體播放器視圖大小
// mPMoviePlayerViewController.view.bounds = CGRectMake(0, 0, 350, 300);
// mPMoviePlayerViewController.view.center = CGPointMake(CGRectGetMidX(self.view.bounds), 64 + CGRectGetMidY(mPMoviePlayerViewController.view.bounds) + 30);
// 4、推送播放
// 推送至媒體播放器進行播放
[self presentViewController:mPMoviePlayerViewController animated:YES completion:nil];
// 直接在本視圖控制器播放
// [self addChildViewController:mPMoviePlayerViewController];
// [self.view addSubview:mPMoviePlayerViewController.view];
}