标签:
在iOS開發上,如果遇到需要播放影片,如開機動畫…,我們很習慣地會使用MediaPlayer來播放影片,因為很方便使用,所以就一直使用下去。但是 隨著客戶的要求越來越嚴苛,尤其是過場動畫或互動效果上的表現。所以如果在一些動畫中還挾帶影片一起運算,那勢必機器會跑不動。所以在iOS 4之後,我們可以使用AVPlayer這個類別來進行更細微的操作。
備註:
請參考以下的範例:
使用MediaPlayer來播放影片
使用AVPlayer來播放影片
MPMoviePlayerController是通过MediaPlayer.frame引入的,可用于播放在iOS支持的所有格式的视频,用起来很简单,但是有注意的事项,实现结果如下:
代码如下:
-(IBAction)click:(id)sender{
//通过点击按钮出发视频播放视图的加载
[self playMyVedio];
}
-(void)playMyVedio{
//路径的设置,这里要注意,不要用[NSURL urlwithstring],还要去确保路径的正确
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:@"111/Viva" ofType:@"mp4"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
//很重要的一点是在头文件里已经把player变为属性了,@property(nonamaic,strong),如果不写为属性就会黑屏,目前不知道为什么
player =[[MPMoviePlayerController alloc] initWithContentURL:movieURL];
player.controlStyle=MPMovieControlStyleDefault;
[player prepareToPlay];
[player.view setFrame:self.view.bounds]; // player的尺寸
[self.view addSubview: player.view];
player.shouldAutoplay=YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen:) name: MPMoviePlayerDidExitFullscreenNotification object:nil];
}
-(void)exitFullScreen:(NSNotification *)notification{
[player.view removeFromSuperview];
NSLog(@”remove player”);
}
更新一种方法,程序启动自动播放全屏视频,没有控制条,播放完毕接视图呈现,也就是一个过场动画,这里要注意把设置控制条和全屏等语句写在添加播放器视图之后,要不然设置无效
-(void)playMyVedio{
NSString *myFilePath = [[NSBundle mainBundle] pathForResource:@”mnMovnew.mp4″ ofType:nil inDirectory:nil];
NSURL *movieURL = [NSURL fileURLWithPath:myFilePath];
player =[[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[player prepareToPlay];
[self.view addSubview:player.view];//设置写在添加之后
player.shouldAutoplay=YES;
[player setControlStyle:MPMovieControlStyleNone];
[player setFullscreen:YES];
[player.view setFrame:self.view.bounds];
}
标签:
原文地址:http://www.cnblogs.com/shuxiachahu123/p/5053371.html