一、播放视频
iOS提供了叫做MPMoviePlayerController、MPMoviePlayerViewController的两个类,可以用来轻松播放视频
YouTobe就是用MPMoviePlayerController实现的
MPMoviePlayerViewController只能全屏播放视频
上述两个类都定义在了MediaPlayer框架中
二、MPMoviePlayerController支持的格式
MPMoviePlayerController继承自NSObject,它内部有个view用来展示视频内容,添加其他控制器的view上面即可显示
MPMoviePlayerController可以播放的视频格式有以下两种:
H.264
MPEG-4 Part 2 video
支持的文件拓展名为:avi,mkv,mov,m4v,mp4等
可以到苹果官网:http://support.apple.com/kb/HT1425下载一些用来测试的视频文件,文件都比较小
三、MPMoviePlayerController-01-加载资源
// 加载视频资源
NSString *urlString = [[NSBundle mainBundle] pathForResource:@"sample_iTunes" ofType:@"mov"];
NSURL *url = [NSURL fileURLWithPath:urlString];
// 创建播放器
_player = [[MPMoviePlayerController alloc] initWithContentURL:url];
四、MPMoviePlayerController-02-显示
// 设置尺寸
_player.view.frame = self.view.bounds;
_player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// 添加到控制器的view上
[self.view addSubview:_player.view];
// 播放
[_player play];
五、MPMoviePlayerController-03-添加通知监听
// 监听播放状态的改变
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoStateChange) name:MPMoviePlayerPlaybackStateDidChangeNotification object:_player];
// 监听播放器结束全屏
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullscreen) name:MPMoviePlayerDidExitFullscreenNotification object:_player];
六、MPMoviePlayerController其他属性
是否要自动播放
@property(nonatomic) BOOL shouldAutoplay;
全屏显示
@property(nonatomic, getter=isFullscreen) BOOL fullscreen;
- (void)setFullscreen:(BOOL)fullscreen animated:(BOOL)animated;
截取视频中的图片
- (void)requestThumbnailImagesAtTimes:(NSArray *)playbackTimes timeOption:(MPMovieTimeOption)option;
七、MPMoviePlayerViewController
MPMoviePlayerViewController继承自UIViewController,它内部封装了一个MPMoviePlayerController
MPMoviePlayerViewController只能全屏播放
简单使用:
MPMoviePlayerViewController *play = [[MPMoviePlayerViewController alloc] initWithContentURL:url];