1.导入<MediaPlayer/MediaPlayer.h>头文件
2.通过MPMoviePlayerViewController为我们提供的两种方式:带视图和不带视图
__带视图(MPMoviePlayerViewController) : __系统已经封装好,可以拿来直接使用
创建控制器->modal展示
__不带视图(MPMoviePlayerController) : __ 可以满足自定义的需求
MPMoviePlayerController和MPMoviePlayerViewController在iOS 9下目前已经过期
带视图的示例代码:
- (IBAction)clickStartPlayButton:(UIButton *)sender {
// 获取视频路径 (这里使用了本地视频文件,如果使用网络视频,设置网络视频URL即可)
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"minion_01.mp4" ofType:nil];
// 带视图
// 创建控制器
MPMoviePlayerViewController *playerViewController = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:filePath]];
// 进行modal展示
[self presentViewController:playerViewController animated:YES completion:nil];
}
在界面上添加了一个开始播放按钮,点击时进行视频播放:
而且默认的媒体控制系统已经帮我们处理好,点击Done会自动dismiss
MPMoviePlayerViewController中包含一个moviePlayer属性
@property (nonatomic, readonly) MPMoviePlayerController *moviePlayer;
MPMoviePlayerController继承自NSObject,所以不能直接进行present,通过<MPMediaPlayback>协议实现播放
不带视图的示例代码:
声明一个强引用类型的属性:
方式一中带有视图的控制器是通过当前控制器modal展现,也就是Self强引用了MPMoviePlayerViewController,保证了MPMoviePlayerViewController不会被释放
同理这里为了保证MPMoviePlayerController不被销毁,所以声明了一个强引用的属性
@property(nonatomic,strong) MPMoviePlayerController *playerController;
按钮点击事件中:
- (IBAction)clickStartPlayButton:(UIButton *)sender {
// 不带视图 (可以自定义视图)
// 获取视频路径 (这里使用了本地视频文件,如果使用网络视频,设置网络视频URL即可)
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"minion_01.mp4" ofType:nil];
// 创建播放器
self.playerController = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:filePath]];
// 准备播放
[self.playerController prepareToPlay];
// 开始播放
[self.playerController play];
}
这样虽然能够实现视频播放,但是只能听到声音,因为还未设置视图
// 设置视图
self.playerController.view.frame = [UIScreen mainScreen].bounds;
[self.view addSubview:self.playerController.view];
这样就能显示视图了:
底部的媒体按钮也是可以直接使用的,右下角按钮点击还能进入全屏:
主要区别在于全屏模式上面会多出一个视图:
进入全屏后,媒体按钮系统都已经帮我们实现好了
Done按钮点击后,会退出全屏,并自动暂停视频
这里设置的是屏幕尺寸,如果需要设置窗口模式,手动给视图设置一个尺寸即可
self.playerController.view.frame = CGRectMake(100, 50, 200, 200);
上面提到了,当自定义窗口视图后,进入全屏播放,点击左上角的Done按钮,会恢复窗口模式,暂停视图,做进一步处理,当点击Done按钮时,恢复窗口模式并销毁视图
实现方式:
1.监听视频控制器(从全屏恢复窗口)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stop) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
2监听到状态变化后进一步判断
全屏模式除了点击Done按钮会退出全屏,右上角也有一个退出全屏的按钮
区别在于:点击Done后会自动停止播放,当退出全屏并暂停播放时就是我们需要的状态,接下来就是移除自定义的播放视频视图
- (void)stop{
switch (self.playerController.playbackState) {
/*
MPMoviePlaybackStateStopped, 停止
MPMoviePlaybackStatePlaying, 正在播放
MPMoviePlaybackStatePaused, 暂停
MPMoviePlaybackStateInterrupted, 中断
MPMoviePlaybackStateSeekingForward, 快进
MPMoviePlaybackStateSeekingBackward 快退
*/
case MPMoviePlaybackStatePaused: //退出全屏&状态为暂停时,才是点击Done按钮
[self.playerController.view removeFromSuperview];
break;
default:
break;
}
}
完整实例代码:
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h> //对<AVFoundation/AVFoundation.h>的封装
@interface ViewController ()
@property(nonatomic,strong) MPMoviePlayerController *playerController;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 监听窗口状态 监听通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stop) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
}
- (void)stop{
switch (self.playerController.playbackState) {
/*
MPMoviePlaybackStateStopped, 停止
MPMoviePlaybackStatePlaying, 正在播放
MPMoviePlaybackStatePaused, 暂停
MPMoviePlaybackStateInterrupted, 中断
MPMoviePlaybackStateSeekingForward, 快进
MPMoviePlaybackStateSeekingBackward 快退
*/
case MPMoviePlaybackStatePaused: //退出全屏&状态为暂停时,才是点击Done按钮
[self.playerController.view removeFromSuperview];
break;
default:
break;
}
}
// 开始播放
- (IBAction)clickStartPlayButton:(UIButton *)sender {
// 不带视图 (可以自定义视图)
// 获取视频路径 (这里使用了本地视频文件,如果使用网络视频,设置网络视频URL即可)
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"minion_01.mp4" ofType:nil];
// 创建播放器
self.playerController = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:filePath]];
// 设置视图
// self.playerController.view.frame = [UIScreen mainScreen].bounds;
self.playerController.view.frame = CGRectMake(100, 50, 200, 200);
[self.view addSubview:self.playerController.view];
// 准备播放
[self.playerController prepareToPlay];
// 开始播放
[self.playerController play];
}
@end
- MPMoviePlayerController中的关键属性说明:
@interface MPMoviePlayerController : NSObject <MPMediaPlayback>
// 视频文件URL
@property (nonatomic, copy) NSURL *contentURL;
// 显示视频的视图
@property (nonatomic, readonly) UIView *view;
// 播放视频的背景视图
@property (nonatomic, readonly) UIView *backgroundView;
// 播放状态
@property (nonatomic, readonly) MPMoviePlaybackState playbackState;
// 加载状态(加载是否成功)
@property (nonatomic, readonly) MPMovieLoadState loadState;
// 控制样式(默认显示)
MPMovieControlStyleNone, // No controls (不显示控制条)
MPMovieControlStyleEmbedded, // Controls for an embedded view(默认)
MPMovieControlStyleFullscreen, // Controls for fullscreen playback
@property (nonatomic) MPMovieControlStyle controlStyle;
// 重复
@property (nonatomic) MPMovieRepeatMode repeatMode;
// 是否自动播放
@property (nonatomic) BOOL shouldAutoplay;
// 缩放 Defaults to MPMovieScalingModeAspectFit.
@property (nonatomic) MPMovieScalingMode scalingMode;
@end
@interface MPMoviePlayerController (MPMovieProperties)
// The types of media in the movie, or MPMovieMediaTypeNone if not known.
@property (nonatomic, readonly) MPMovieMediaTypeMask movieMediaTypes NS_DEPRECATED_IOS(2_0, 9_0, "Use AVPlayerViewController in AVKit.");
// The playback type of the movie. Defaults to MPMovieSourceTypeUnknown.
// Specifying a playback type before playing the movie can result in faster load times.
@property (nonatomic) MPMovieSourceType movieSourceType NS_DEPRECATED_IOS(2_0, 9_0, "Use AVPlayerViewController in AVKit.")
;
// The duration of the movie, or 0.0 if not known.
@property (nonatomic, readonly) NSTimeInterval duration NS_DEPRECATED_IOS(2_0, 9_0, "Use AVPlayerViewController in AVKit.")
;
// The currently playable duration of the movie, for progressively downloaded network content.
@property (nonatomic, readonly) NSTimeInterval playableDuration NS_DEPRECATED_IOS(2_0, 9_0, "Use AVPlayerViewController in AVKit.")
;
// The natural size of the movie, or CGSizeZero if not known/applicable.
@property (nonatomic, readonly) CGSize naturalSize NS_DEPRECATED_IOS(2_0, 9_0, "Use AVPlayerViewController in AVKit.")
;
// The start time of movie playback. Defaults to NaN, indicating the natural start time of the movie.
@property (nonatomic) NSTimeInterval initialPlaybackTime NS_DEPRECATED_IOS(2_0, 9_0, "Use AVPlayerViewController in AVKit.")
;
// The end time of movie playback. Defaults to NaN, which indicates natural end time of the movie.
@property (nonatomic) NSTimeInterval endPlaybackTime NS_DEPRECATED_IOS(2_0, 9_0, "Use AVPlayerViewController in AVKit.")
;
// Indicates whether the movie player allows AirPlay video playback. Defaults to YES on iOS 5.0 and later.
@property (nonatomic) BOOL allowsAirPlay NS_DEPRECATED_IOS(4_3, 9_0, "Use AVPlayerViewController in AVKit.")
;
//
@property (nonatomic, readonly, getter=isAirPlayVideoActive) BOOL airPlayVideoActive ;
@end
如果想要使用自定义的控制条样式
可以设置controlStyle为MPMovieControlStyleNone,然后添加自定义的媒体控制视图
需要注意的是:需要把事件添加到view视图上, backgroundView下是不能监听事件
在view属性中已经给了说明
// The view in which the media and playback controls are displayed.
@property (nonatomic, readonly) UIView *view;
如果想要修改背景视图,可以设置backgroundView
如果需要播放时默认进入全屏,在播放按钮事件中,还可以重新设置播放视频视图的Frame为屏幕的bounds,并让其旋转90°,示例代码:
[UIView animateWithDuration:0.1 animations:^{
// 播放视图全屏横向显示
self.playerController.view.transform = CGAffineTransformRotate(self.playerController.view.transform, M_PI_2);
// 设置全屏
self.playerController.view.frame = [UIScreen mainScreen].bounds;
}];
MPMediaPlayback协议内容:
@protocol MPMediaPlayback
// Prepares the current queue for playback, interrupting any active (non-mixible) audio sessions.
// Automatically invoked when -play is called if the player is not already prepared.
- (void)prepareToPlay;
// Returns YES if prepared for playback.
@property(nonatomic, readonly) BOOL isPreparedToPlay;
// Plays items from the current queue, resuming paused playback if possible.
- (void)play;
// Pauses playback if playing.
- (void)pause;
// Ends playback. Calling -play again will start from the beginnning of the queue.
- (void)stop;
// The current playback time of the now playing item in seconds.
@property(nonatomic) NSTimeInterval currentPlaybackTime;
// The current playback rate of the now playing item. Default is 1.0 (normal speed).
// Pausing will set the rate to 0.0. Setting the rate to non-zero implies playing.
@property(nonatomic) float currentPlaybackRate;
// The seeking rate will increase the longer scanning is active.
- (void)beginSeekingForward;
- (void)beginSeekingBackward;
- (void)endSeeking;
@end
// Posted when the prepared state changes of an object conforming to the MPMediaPlayback protocol changes.
// This supersedes MPMoviePlayerContentPreloadDidFinishNotification.
MP_EXTERN __TVOS_PROHIBITED NSString *const MPMediaPlaybackIsPreparedToPlayDidChangeNotification NS_DEPRECATED_IOS(3_2, 9_0);