iOS使用AVPlayer及MPPlayer播放在线视频

前言

最近在仿做一个APP,其中使用到视频流播放,原本是打算使用MPPlayer进行在线播放出来的,但是发现iOS9之后以及不在支持MP了,刚好也没怎么接触过AVPlyer借此机会刚好学习一番。因为AVPlayer所有控件都是需要自定义,如果只是简单的播放视频其实是不如MPPlayer方便的。

实现过程

1. 简单点的MPPlayer

  • 声明一个MPMoviePlayerController 的属性
1
2
@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;
@property (nonatomic, strong) NSString *moviePath;//播放路径
  • 懒加载
1
2
3
4
5
6
7
8
9
10
11
if (!_moviePlayer) {
_moviePlayer = [[MPMoviePlayerController alloc]init];
[_moviePlayer.view setFrame:CGRectMake(0, 300, self.view.bounds.size.width, self.view.bounds.size.height/3)];
//设置自动播放
[_moviePlayer setShouldAutoplay:NO];
//设置源类型 因为新特性一般都是播放本地的小视频 所以设置源类型为file
_moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
[self.view addSubview:_moviePlayer.view];
}
return _moviePlayer;

如果只是播放暂停之类的几乎是不需要自己做什么的,很简单。

  • 设置播放源
    我是在set方法中设置的,不过这个都无所谓。
1
2
3
4
5
6
7
8
- (void)setMoviePath:(NSString *)moviePath{
_moviePath = [moviePath copy];
self.moviePlayer.view.backgroundColor = [UIColor clearColor];
// 设置播放的路径
self.moviePlayer.contentURL = [NSURL URLWithString:moviePath];
[self.moviePlayer prepareToPlay];
[self.moviePlayer play];
}
  • viewDidLoad调用
1
self.moviePath = @"http://baobab.wdjcdn.com/1455782903700jy.mp4";
  • 大功告成

MPPlyer播放

2.主角AVPlayer

  • AVPlayer需要的属性,这是播放器基础
1
2
3
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
  • 实现AVPlayer播放
1
2
3
4
5
6
7
NSURL *url = [NSURL URLWithString:_playerUrl];
_item = [[AVPlayerItem alloc] initWithURL:url];
_player = [AVPlayer playerWithPlayerItem:_item];
_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
_playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.layer addSublayer:_playerLayer];
[_player play];

虽然是可以播放视频了但仅仅是能播放而已,暂停播放快进等功能都没有,下面对他进行完善。

  • 添加底部工具栏
1
2
3
4
5
6
7
8
9
10
11
@property (nonatomic, strong) UIView *toolView;//工具栏
@property (nonatomic, strong) UISlider *slider;//用来现实视频的播放进度
@property (nonatomic, assign) BOOL isShowToolView;//是否显示工具栏
@property (nonatomic, strong) UIButton *playOrPause;//播放暂停按钮
@property (nonatomic, strong) NSTimer *showTimer;//显示工具栏时间
@property (nonatomic, strong) NSTimer *progressTimer;//进度条计时器
@property (nonatomic, strong) UILabel *timerLabel;//播放时间
@property (nonatomic, strong) UILabel *allTimeLabel;//总时间
@property (nonatomic, strong) UIButton *bigPlayBtn;//中间播放按钮
@property (nonatomic, strong) UIView *coverView;//遮盖版
  • 下面就是界面实现了
1
2
3
4
5
//工具栏
self.toolView = [[UIView alloc]initWithFrame:CGRectMake(0, self.bounds.size.height - kToolViewHieght, self.bounds.size.width, kToolViewHieght)];
self.toolView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
[self addSubview:self.toolView];
[self bringSubviewToFront:self.toolView];
1
2
3
4
5
6
7
8
//播放按钮
self.playOrPause = [UIButton buttonWithType:UIButtonTypeCustom];
[self.playOrPause setImage:[UIImage imageNamed:@"videoplay"] forState:UIControlStateNormal];
[self.playOrPause setImage:[UIImage imageNamed:@"videopause"] forState:UIControlStateSelected];
self.playOrPause.contentMode = UIViewContentModeCenter;
[self.playOrPause addTarget:self action:@selector(playOrPauseClick:) forControlEvents:UIControlEventTouchUpInside];
self.playOrPause.frame = CGRectMake(0, 0, 30, kToolViewHieght);
[self.toolView addSubview:self.playOrPause];
  • 其他控件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
self.timerLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, 40, kToolViewHieght)];
self.timerLabel.font = [UIFont systemFontOfSize:10.0];
self.timerLabel.textColor = [UIColor whiteColor];
[self.toolView addSubview:self.timerLabel];
self.allTimeLabel =[[UILabel alloc]initWithFrame:CGRectMake(70, 0, 40, kToolViewHieght)];
self.allTimeLabel.font = [UIFont systemFontOfSize:10.0];
self.allTimeLabel.textColor = [UIColor whiteColor];
[self.toolView addSubview:self.allTimeLabel];
self.bigPlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.bigPlayBtn setImage:[UIImage imageNamed:@"videoplay"] forState:UIControlStateNormal];
[self.bigPlayBtn addTarget:self action:@selector(playOrPauseBigClick:) forControlEvents:UIControlEventTouchUpInside];
self.bigPlayBtn.frame = self.bounds;
self.bigPlayBtn.contentMode = UIViewContentModeScaleAspectFill;
[self addSubview:self.bigPlayBtn];
self.coverView.hidden = YES;
self.toolView.alpha = 0;
self.isShowToolView = NO;
self.playOrPause.selected = NO;
  • 进度条
1
2
3
4
5
6
7
8
9
10
11
12
13
//懒加载进度条
- (UISlider *)slider{
if (!_slider) {
_slider.backgroundColor = [UIColor whiteColor];
_slider = [[UISlider alloc]initWithFrame:CGRectMake(110, 0, 200, kToolViewHieght)];
//设置slider原点已经最大点最小点图片
[_slider setThumbImage:[UIImage imageNamed:@"videothumb"] forState:UIControlStateNormal];
[_slider addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
[_slider addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
[_slider addTarget:self action:@selector(touchUpInside:) forControlEvents:UIControlEventTouchUpInside];
}
return _slider;
}
  • 进度条点击方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)touchDown:(UISlider *)slider{
// 按下去 移除监听器
[self removeProgressTimer];
[self removeShowTime];
}
- (void)valueChange:(UISlider *)slider{
NSTimeInterval currentTime = CMTimeGetSeconds(self.player.currentItem.duration) * slider.value;
self.timerLabel.text = [self timeToStringWithTimeInterval:currentTime];
}
- (void)touchUpInside:(UISlider *)slider{
[self addProgressTimer];
//计算当前slider拖动对应的播放时间
NSTimeInterval currentTime = CMTimeGetSeconds(self.player.currentItem.duration) * slider.value;
// seekToTime:播放跳转到当前播放时间
[self.player seekToTime:CMTimeMakeWithSeconds(currentTime, NSEC_PER_SEC) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
[self toolViewShow];
}
  • slider定时器
1
2
3
4
5
6
7
- (NSTimer *)progressTimer{
if (!_progressTimer) {
_progressTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateProgressInfo) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop]addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
}
return _progressTimer;
}
  • 更新slider和time
1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)updateProgressInfo{
NSTimeInterval currentTime = CMTimeGetSeconds(self.player.currentTime);
NSTimeInterval durationTime = CMTimeGetSeconds(self.player.currentItem.duration);
self.timerLabel.text = [self timeToStringWithTimeInterval:currentTime];
self.allTimeLabel.text = [self timeToStringWithTimeInterval:durationTime];
self.slider.value = CMTimeGetSeconds(self.player.currentTime)/CMTimeGetSeconds(self.player.currentItem.duration);
if (self.slider.value == 1) {
[self removeProgressTimer];
self.coverView.hidden = NO;
}
}
  • 移除slider定时器
1
2
3
4
5
//移除slider定时器
- (void)removeProgressTimer{
[self.progressTimer invalidate];
self.progressTimer = nil;
}
  • 播放器的手势点击
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//手势点击
- (void)playTap:(UITapGestureRecognizer *)tap{
//未播放状态,点击view会直接播放
if (self.player.status == AVPlayerStatusUnknown) {
[self playOrPauseClick:self.playOrPause];
return;
}
//记录工具栏的是否隐藏
self.isShowToolView = !self.isShowToolView;
if (self.isShowToolView) {
[UIView animateWithDuration:0.5 animations:^{
self.toolView.alpha = 0.8;
}];
//工具栏的按钮为播放状态是,添加计时器,5秒之后自动隐藏
if (self.playOrPause.selected) {
[self toolViewShow];
}
}else{
[self removeShowTime];
[UIView animateWithDuration:0.5 animations:^{
self.toolView.alpha = 0;
}];
}
}
  • 播放按钮方法
1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)playOrPauseClick:(UIButton *)btn{
btn.selected = !btn.selected;
if (!btn.selected) {
self.toolView.alpha = 0.8;
[self removeShowTime];
[self.player pause];
[self removeProgressTimer];
}else{
[self toolViewShow];
[self.player play];
[self addProgressTimer];
}
}
  • 中间播放按钮的方法
1
2
3
4
5
6
7
8
//中间播放按钮的方法
- (void)playOrPauseBigClick:(UIButton *)btn{
btn.hidden = YES;
self.playOrPause.selected = YES;
[self.player replaceCurrentItemWithPlayerItem:self.playerItem];
[self.player play];
[self addProgressTimer];
}
  • 工具栏的显示及隐藏
1
2
3
4
5
6
7
8
9
10
11
- (void)toolViewShow{
self.showTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(toolViewHide) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop]addTimer:self.showTimer forMode:NSRunLoopCommonModes];
}
- (void)toolViewHide{
self.isShowToolView = !self.isShowToolView;
[UIView animateWithDuration:0.5 animations:^{
self.toolView.alpha = 0;
}];
NSLog(@"工具栏隐藏");
}
  • 添加遮罩视图用于播放完成后
1
2
3
4
5
6
7
8
9
10
- (UIView *)coverView{
if (!_coverView) {
_coverView = [UIView new];
_coverView.center = self.center;
_coverView.bounds = CGRectMake(0, 0, 100, 100);
_coverView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.9];
[self addSubview:_coverView];
}
return _coverView;
}
  • 在遮罩视图上添加重播按钮
1
2
3
4
5
6
UIButton *ReplayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[ReplayBtn setImage:[UIImage imageNamed:@"chongshe"] forState:UIControlStateNormal];
ReplayBtn.center = self.coverView.center;
ReplayBtn.frame = CGRectMake(0, 0, 100, 100);
[ReplayBtn addTarget:self action:@selector(rePlayClick) forControlEvents:UIControlEventTouchUpInside];
[self.coverView addSubview:ReplayBtn];
  • 重播按钮的方法
1
2
3
4
5
6
- (void)rePlayClick{
self.slider.value = 0;
[self touchUpInside:self.slider];
self.coverView.hidden = YES;
[self playOrPauseBigClick:self.bigPlayBtn];
}
  • 到这里一个带有播放暂停重播等基本功能的播发器就完成了

完成效果图

后记

  • 上面是我用AVPlayer实现播放的一点心得。demo做的很简陋,有诸多的不足,需要完善的地方也有很多,主要是为了给大家提供一个思路抛砖引玉,希望可以帮到大家。
  • 惯例放上项目源码还有我的个人网站,有需要的可以去看一下。
  • 参考文章iOS-视频播放器的简单封装