用MPMoviePlayerController播放视频的方法

来源:互联网 发布:node执行js文件 编辑:程序博客网 时间:2024/05/11 19:07

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;

}

如果注意了视频的路径,和设置了属性,那么点击按钮就应该可以顺利的以全屏幕是播放视频,下一个问题就是退出,因为是全屏模式,模仿 iphone自己的视频播放,应该是点击左上角的done按钮就退出播放,这里如果不作处理,点击后只是退出全屏,屏幕还是有一块黑,其实是player 的非全屏模式,所以这里就要监听一个通知,点击done按钮后发出的通知,这样就可以退出了,代码如下:

- (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://blog.sina.com.cn/s/blog_a7c44c8801017k40.html

原创粉丝点击