// // MOLVideoViewController.m // STLBGVideo // // Created by StoneLeon on 16/1/13. // Copyright © 2016年 StoneLeon. All rights reserved. // #import "MOLVideoViewController.h" #import "MOLVideoFunctions.h" #define CurrentSystemVersion ([[[UIDevice currentDevice] systemVersion] floatValue]) @interface MOLVideoViewController () @property (nonatomic, strong) AVPlayer *player; @property (nonatomic, strong) AVPlayerLayer *playerLayer; @property (nonatomic,assign) BOOL isLoop; @end @implementation MOLVideoViewController #pragma mark - Player - (void)getPlayerNotifications { // 添加播放结束通知,循环播放 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem]; // APP进入活跃态的通知 ReceiveNotification(@selector(toCheckThePlayerStatusAndGoPlay), UIApplicationDidBecomeActiveNotification) } - (void)toCheckThePlayerStatusAndGoPlay{ //APP进入活跃状态, 检查播放器, 判断是否在播放, 如果暂停则继续播放 if(_player){ if (_player.rate != 0 && _player.error == nil){ MOLogV(@"AVPlayer is playing"); } else{ MOLogV(@"AVPlayer is not playing"); [_player play]; } } } - (void)preparePlayback { if (self.player == nil) { NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[MOLVideoFunctions getVideoUrl] ofType:[MOLVideoFunctions getVideoType]]]; // 初始化 AVPlayer AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:videoURL]; self.player = [AVPlayer playerWithPlayerItem:playerItem]; // 创建 AVPlayerLayer 并设置其属性 self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player]; self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; self.playerLayer.frame = CGRectMake(0.0, 0.0, SCREENWIDTH, SCREENHEIGHT); // 将 AVPlayerLayer 添加到视图的底层 [self.view.layer insertSublayer:self.playerLayer atIndex:0]; // 开始播放 [self.player play]; } } - (void)dealloc { // 停止并释放 AVPlayer [self.player pause]; [self.player.currentItem cancelPendingSeeks]; [self.player.currentItem.asset cancelLoading]; self.player = nil; } // 播放结束通知的处理方法 - (void)playerDidFinishPlaying:(NSNotification *)notification { // 将播放头设置回视频的起始位置,实现循环播放 [self.player seekToTime:kCMTimeZero]; [self.player play]; } #pragma mark - life cycle - (void)viewDidLoad { [super viewDidLoad]; if ([MOLVideoFunctions getUrlInfo] != nil) { self.isLoop = [MOLVideoFunctions getLoopMode]; [self preparePlayback]; } } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self getPlayerNotifications]; [self.player play]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self.player pause]; } @end