在iOS9以后,MPMoviePlayerViewController被弃用,苹果推荐我们使用AVPlayerViewControlller,下面我们来了解一下AVPlayerViewController的使用方法。
在我们了解AVPlayerViewController之前,先要了解AVPlayer和AVPlayerItem。
一、AVPlayer
以下为AVPlayer官方文档对AVPlayer的介绍。
An AVPlayer is a controller object used to manage the playback and timing of a media asset. It provides the interface to control the player’s transport behavior such as its ability to play, pause, change the playback rate, and seek to various points in time within the media’s timeline. You can use an AVPlayer to play local and remote file-based media, such as QuickTime movies and MP3 audio files, as well as audiovisual media served using HTTP Live Streaming.
可以看到,AVPlayer是一个控制器,可以实现音视频播放的基本需求,️️️
AVPlayer不仅可以播放本地音视频,还可以播放HTTP流媒体。
AVPlayer可以实现播放,暂停,改变播放速率,在视频的时间线上进行跳转。
AVPlayer的初始化有四种方式:
-initWithURL: 初始化一个player。可以播放单个的视听资源。传入一个URL。
+playerWithURL: 返回一个player。可以播放单个的视听资源。传入一个URL。
-initWithPlayerItem: 初始化一个player。可以播放特定的AVPlayerItem。
+playerWithPlayerItem: 返回一个player。可以播放特定的AVPlayerItem。
如果通过传入URL的方式,则不能修改视频播放源。传入AVplayerItem则可以通过replaceCurrentItemWithPlayerItem:修改currentItem来修改播放源。
下面是使用AVPlayer播放本地视频的代码。
//ViewContoller.m
#import <UIKit/UIKit.h>
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <time.h>
@interface ViewController ()
@property (strong,nonatomic) AVPlayerViewController *moviePlayer;
@property (strong,nonatomic) AVPlayer *player;
@property (strong,nonatomic) AVPlayerItem *item;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor=[UIColor whiteColor];
//设置本地视频路径
NSString *mpath=[[NSBundle mainBundle] pathForResource:@"a" ofType:@"mp4"];
NSURL *url=[NSURL fileURLWithPath:mpath];
AVAsset *asset = [AVAsset assetWithURL:url];
self.item=[AVPlayerItem playerItemWithAsset:asset];
//设置流媒体视频路径
//self.item=[AVPlayerItem playerItemWithURL:movieURL];
//设置AVPlayer中的AVPlayerItem
self.player=[AVPlayer playerWithPlayerItem:self.item];
//初始化layer 传入player
AVPlayerLayer *layer=[AVPlayerLayer playerLayerWithPlayer:self.player];
//设置layer的属性
layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
layer.contentsScale = [UIScreen mainScreen].scale;
layer.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2);
layer.backgroundColor=[UIColor greenColor].CGColor;
//将视频的layer添加到视图的layer中
[self.view.layer addSublayer:layer];
//替换AVPlayer中的AVPlayerItem
//[self.player replaceCurrentItemWithPlayerItem:self.item];
//监听status属性,注意监听的是AVPlayerItem
[self.item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//监听loadedTimeRanges属性
[self.item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}
//AVPlayerItem监听的回调函数
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
AVPlayerItem *playerItem = (AVPlayerItem *)object;
if ([keyPath isEqualToString:@"loadedTimeRanges"]){
}else if ([keyPath isEqualToString:@"status"]){
if (playerItem.status == AVPlayerItemStatusReadyToPlay){
NSLog(@"playerItem is ready");
//如果视频准备好 就开始播放
[self.player play];
} else if(playerItem.status==AVPlayerStatusUnknown){
NSLog(@"playerItem Unknown错误");
}
else if (playerItem.status==AVPlayerStatusFailed){
NSLog(@"playerItem 失败");
}
}
}
二、AVPlayerVIewController
以下为AVPlayerViewController官方文档对AVPlayer的介绍。
Using AVPlayerViewController makes it easy for you to add media playback capabilities to your application matching the styling and features of the native system players. Since AVPlayerViewController is a system framework class, your playback applications automatically adopt the new aesthetics and features of future operating system updates without any additional work from you.
****AVPlayerViewController继承自UIViewController,但是如果直接把AVPlayerViewController当做UIViewController添加到UIWindow的话,不会显示视频控制栏,正确的代码如下****
//moviewPlayer就是一个AVPlayerViewController
self.moviePlayer=[[AVPlayerViewController alloc]init];
//设置AVPlayerViewController的player
self.moviePlayer.player=self.player;
//把AVPlayerViewController的view添加到UIViewController的view中
[self.view addSubview:self.moviePlayer.view];
另外,AVPlayerViewController有以下几个常用属性️
showsPlaybackControls:BOOL属性,默认值为YES,设置是否显示控制栏
videoGravity:设置视频的缩放格式,默认值为AVLayerVideoGravityResizeAspect,包括以下三种:
AVLayerVideoGravityResizeAspect
AVLayerVideoGravityResizeAspectFill
AVLayerVideoGravityResize
话不多说,下面贴代码:
//ViewContoller.m
#import <UIKit/UIKit.h>
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <time.h>
@interface ViewController ()
@property (strong,nonatomic) AVPlayerViewController *moviePlayer;
@property (strong,nonatomic) AVPlayer *player;
@property (strong,nonatomic) AVPlayerItem *item;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor=[UIColor whiteColor];
//设置本地视频路径
NSString *mpath=[[NSBundle mainBundle] pathForResource:@"a" ofType:@"mp4"];
NSURL *url=[NSURL fileURLWithPath:mpath];
AVAsset *asset = [AVAsset assetWithURL:url];
self.item=[AVPlayerItem playerItemWithAsset:asset];
//设置流媒体视频路径
//self.item=[AVPlayerItem playerItemWithURL:movieURL];
//设置AVPlayer中的AVPlayerItem
self.player=[AVPlayer playerWithPlayerItem:self.item];
//初始化AVPlayerViewController
self.moviePlayer=[[AVPlayerViewController alloc]init];
self.moviePlayer.player=self.player;
[self.view addSubview:self.moviePlayer.view];
//设置AVPlayerViewController的frame
self.moviePlayer.view.frame=self.view.frame;
//替换AVPlayer中的AVPlayerItem
//[self.player replaceCurrentItemWithPlayerItem:self.item];
//监听status属性,注意监听的是AVPlayerItem
[self.item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//监听loadedTimeRanges属性
[self.item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//设置监听函数,监听视频播放进度的变化,每播放一秒,回调此函数
__weak __typeof(self) weakSelf = self;
[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//当前播放的时间
NSTimeInterval current = CMTimeGetSeconds(time);
//视频的总时间
NSTimeInterval total = CMTimeGetSeconds(weakSelf.player.currentItem.duration);
//输出当前播放的时间
NSLog(@"now %f",current);
}];
}
//AVPlayerItem监听的回调函数
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
AVPlayerItem *playerItem = (AVPlayerItem *)object;
if ([keyPath isEqualToString:@"loadedTimeRanges"]){
double t=[self availableDurationWithplayerItem:self.item];
NSLog(@"loadranges %f",t);
}else if ([keyPath isEqualToString:@"status"]){
if (playerItem.status == AVPlayerItemStatusReadyToPlay){
NSLog(@"playerItem is ready");
//如果视频准备好 就开始播放
[self.player play];
} else if(playerItem.status==AVPlayerStatusUnknown){
NSLog(@"playerItem Unknown错误");
}
else if (playerItem.status==AVPlayerStatusFailed){
NSLog(@"playerItem 失败");
}
}
}
//计算缓冲进度的函数
- (NSTimeInterval)availableDurationWithplayerItem:(AVPlayerItem *)playerItem
{
NSArray *loadedTimeRanges = [playerItem loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
NSTimeInterval startSeconds = CMTimeGetSeconds(timeRange.start);
NSTimeInterval durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
return result;
}
效果如图