#import 《UIKit/UIKit.h》
#import 《MediaPlayer/MediaPlayer.h》
@interface HeMoviePlayerViewController :UIViewController<</span>UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,retain)MPMoviePlayerController*moviewPlayer;
@end
#import"HeMoviePlayerViewController.h"
#import 《AVFoundation/AVFoundation.h》
@interfaceHeMoviePlayerViewController ()
@property(nonatomic)NSIntegerfileSize;
@property(nonatomic,retain)NSURL*videoURL;
@property(nonatomic,copy)NSString*mp4Path;
@property(nonatomic,retain)NSMutableArray*pathArray;
@property(nonatomic)BOOLisTransformation;
@end
@implementationHeMoviePlayerViewController
- (id)initWithNibName:(NSString *)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil
{
self = [superinitWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custominitialization
_pathArray =[[NSMutableArrayalloc] init];
}
return self;
}
- (void)loadView{
[super loadView];
UIButton*btn= [UIButtonbuttonWithType:UIButtonTypeCustom];
btn.tag = 11;
[btn setFrame:CGRectMake(HBoundWidth/2-30,10,60,40)];
[btn setTitle:@"播放"forState:UIControlStateNormal];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn.backgroundColor =[UIColor orangeColor];
[btn addTarget:selfaction:@selector(playVideo:) forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:btn];
UIButton*btn1= [UIButtonbuttonWithType:UIButtonTypeCustom];
[btn1 setFrame:CGRectMake(btn.right+20,10,60,40)];
[btn1 setTitle:@"暂停"forState:UIControlStateNormal];
[btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn1.backgroundColor =[UIColor orangeColor];
[btn1 addTarget:selfaction:@selector(playVideo:) forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:btn1];
_moviewPlayer= [[MPMoviePlayerController alloc] initWithContentURL:[NSURLfileURLWithPath:[[NSBundle mainBundle] pathForResource:@"popeye" ofType:@"mp4"]]];
// _moviewPlayer.allowsAirPlay= YES; //----重复播放
// _moviewPlayer.view.userInteractionEnabled = NO;
MPMovieControlModeDefault 显示播放/暂停、音量和时间控制
MPMovieControlModeVolumeOnly 只显示音量控制
MPMoviewControlModeHidden 没有控制器
_moviewPlayer.controlStyle= MPMovieControlModeDefault;
MPMoviewScallingModeNone; 不做任何缩放
MPMoviewScallingModeAspectFit 适应屏幕大小,保持宽高比
MPMovieScallingModeAspectFill 适应屏幕大小,保持宽高比,可裁剪
MPMovieScallingModeFill 充满屏幕,不保持宽高比
_moviewPlayer.scalingMode =MPMovieScalingModeFill;
_moviewPlayer.shouldAutoplay= NO; //---设置不自动播放,Defaults to YES.
[_moviewPlayersetFullscreen:YES animated:YES];
[_moviewPlayer.viewsetFrame:CGRectMake(10,50,HBoundWidth-20,300)];
[self.viewaddSubview:_moviewPlayer.view];
UIButton*btn2= [UIButtonbuttonWithType:UIButtonTypeCustom];
[btn2 setFrame:CGRectMake(HBoundWidth/2-30,_moviewPlayer.view.bottom+10,60,40)];
[btn2 setTitle:@"录制"forState:UIControlStateNormal];
[btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn2.backgroundColor =[UIColor orangeColor];
[btn2 addTarget:selfaction:@selector(rerocdVideo:) forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:btn2];
UIButton*btn3= [UIButtonbuttonWithType:UIButtonTypeCustom];
[btn3 setFrame:CGRectMake(btn2.right+20,_moviewPlayer.view.bottom+10,60,40)];
[btn3 setTitle:@"转换"forState:UIControlStateNormal];
[btn3 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn3.backgroundColor =[UIColor orangeColor];
[btn3 addTarget:selfaction:@selector(transformationMovie)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:btn3];
}
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loadingthe view.
[[UIDevicecurrentDevice]beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(deviceOrientationDidChange:)name:UIDeviceOrientationDidChangeNotificationobject:nil];
}
//----控制音量和设置音量
- (UISlider *)getVolumeLevl
{
MPVolumeView *slider = [[MPVolumeView alloc]init];
UISlider *volumViewSlider;
for (UIView *viewin [slider subviews]) {
if ([[[view class] description] isEqualToString:@"MPVolumeSlider"]) {
volumViewSlider = (UISlider*)view;
}
}
return volumViewSlider;
}
- (void)deviceOrientationDidChange:(NSObject*)object
{
UIDevice *device = [object valueForKey:@"object"];
NSLog(@"%d",device.orientation);// 1和2手机都是垂直的,3和4都是横向的,5是平放
}
#pragma mark --------rerocd Video
- (void)rerocdVideo:(UIButton *)button
{
UIImagePickerController *pickerView = [[UIImagePickerControlleralloc]init];
pickerView.sourceType=UIImagePickerControllerSourceTypeCamera;
pickerView.videoQuality=UIImagePickerControllerQualityType640x480; //----在相机这里设置分辨率,那么获得的文件就能以高质量压缩,而视频不会模糊了,压缩的比例为4:1
NSArray*availableMedia = [UIImagePickerControlleravailableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
pickerView.mediaTypes = [NSArrayarrayWithObject:availableMedia[1]]; //---获取你是要用相机还是录像
[selfpresentViewController:pickerView animated:YEScompletion:nil];
pickerView.videoMaximumDuration =30*60; //---设定录制多少秒
pickerView.delegate = self;
}
- (void)playVideo:(UIButton *)btn
{
if (btn.tag ==11) {
if(_videoURL) {
if (_isTransformation) {
_moviewPlayer.contentURL = [NSURLfileURLWithPath:_mp4Path];
}else{
_moviewPlayer.contentURL= _videoURL;
}
CGFloat time = [selfgetVideoDuration:_videoURL];
NSUIntegersecond,minute,hour;
second =(NSUInteger)time %60;
minute =((NSUInteger)time /60) %60;
hour = ((NSUInteger)time /60*60)% 60;
NSLog(@"d:d:d",hour,minute,second);
}
[_moviewPlayerplay];
NSLog(@"mark");
}else{
[_moviewPlayer pause]; //---暂停
}
}
//------播放完成调用
- (void)movieFinishCallBack:(NSNotification *)notification
{
}
- (void)transformationMovie
{
//----经测试一分钟的视频大小为6102KB,格式MOV,使用AVAssetExportPresetLowQuality压缩之后文件大小为1203,比例大约为6:1,倍数为5.072319.
//----经测试,录制视频为mov格式,可以转化为.mp4、.qt、
if (_videoURL) {
AVURLAsset*avAsset = [AVURLAssetURLAssetWithURL:_videoURLoptions:nil];
NSArray*compatiblePresets = [AVAssetExportSessionexportPresetsCompatibleWithAsset:avAsset];
if([compatiblePresetscontainsObject:AVAssetExportPreset640x480]){
UIAlertView *alert =[[UIAlertViewalloc] init];
[alertsetTitle:@"waiting..."];
UIActivityIndicatorView *activi = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activi.frame =CGRectMake(140,80,CGRectGetWidth(alert.frame),CGRectGetHeight(alert.frame));
[alertaddSubview:activi];
[activistartAnimating];
[alertshow];
AVAssetExportSession*exportSession = [[AVAssetExportSessionalloc]initWithAsset:avAssetpresetName:AVAssetExportPresetMediumQuality];
NSDateFormatter *format =[[NSDateFormatteralloc] init];
[formatsetDateFormat:@"yyyy-MM-dd HH:mm:ss"];
_mp4Path =[NSHomeDirectory()stringByAppendingFormat:@"/Documents/output-%@.mp4",[format stringFromDate:[NSDate date]]];
exportSession.outputURL =[NSURLfileURLWithPath:_mp4Path];
exportSession.shouldOptimizeForNetworkUse =YES;
NSArray *array =exportSession.supportedFileTypes;
exportSession.outputFileType =AVFileTypeMPEG4;
[exportSessionexportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
caseAVAssetExportSessionStatusFailed:
{
[alertdismissWithClickedButtonIndex:0animated:NO];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[[exportSession error] localizedDescription]delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil,nil];
[alertshow];
}
break;
caseAVAssetExportSessionStatusCancelled:
[alertdismissWithClickedButtonIndex:0animated:YES];
break;
caseAVAssetExportSessionStatusCompleted:
[activistopAnimating];
[alertdismissWithClickedButtonIndex:0animated:YES];
NSInteger i = [selfgetFileSize:_mp4Path];
NSLog(@"转换之前大小:%d,转换之后大小:%d,倍数为:%f",_fileSize,i,(float)_fileSize/(float)i);
NSLog(@"已转换成功....");
NSLog(@"%@",_mp4Path);
_isTransformation =YES;
break;
default:
break;
}
}];
}
}
}
#pragma mark --------UIImagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)pickerdidFinishPickingMediaWithInfo:(NSDictionary *)info
{
_videoURL=info[UIImagePickerControllerMediaURL];
[_pathArray addObject:_videoURL]; //----把文件路径存储进入队列
_fileSize=[self getFileSize:[[_videoURL absoluteString] substringFromIndex:16]];
NSLog(@"%ld",(long)_fileSize);
NSLog(@"%f",[selfgetVideoDuration:_videoURL]);
NSLog(@"%@",_videoURL);
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
{
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// _moviewPlayer.currentPlaybackTime = 30;
NSLog(@"%f",_moviewPlayer.currentPlaybackTime);
NSLog(@"moview player!");
UISlider *slider = [selfgetVolumeLevl];
NSLog(@"%f", slider.value =0.8);
}
//-------获取视频文件大小,单位KB
- (NSInteger)getFileSize:(NSString *)path
{
NSFileManager *fileManager = [[NSFileManageralloc] init];
if ([fileManager fileExistsAtPath:path]) {
NSDictionary*attributes = [fileManagerattributesOfItemAtPath:path error:nil];
NSNumber*fileSize;
if((fileSize = [attributesobjectForKey:NSFileSize])) {
return fileSize.intValue/1024;
}else{
return -1;
}
}else{
return-1;
}
}
//-------获取视频文件时长
- (CGFloat)getVideoDuration:(NSURL *)url
{
NSDictionary *dic = [NSDictionary dictionaryWithObject:[NSNumbernumberWithBool:NO]forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *urlAsset = [AVURLAssetURLAssetWithURL:url options:dic];
CGFloat second = 0;
second =urlAsset.duration.value/urlAsset.duration.timescale; //----单位s
return second;
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can berecreated.
}
@end