AVPlayerViewController

2017-09-29  本文已影响0人  维若

demo地址:https://github.com/xuaimian/AVPlayerViewController.git

看到网上很多都说,avplayer的layer没有创建,所以无法加载页面,估计是探路人一个人理解错了,导致很多人理解错了吧。其实不是这样的,是avplayerviewcontroller没有经过viewdidappear 直接add,导致avplayerviewcontroller的view 不能获得frame的大小,导致我们感觉没有add上去,其实只要设置一下view的frame就好了。

方法一:

注意点:

1._controller要声明成全局变量,不然无法控制播放。不声明成全局变量,要想办法retain一下,比如,self addchildcontrollers.

2.addobserver的时候,不要传object,这时候传递的object是指的发送方,而不是参数。当postnotification的对象与object不一致时,是不会响应通知方法的。

_controller= [[AVPlayerViewController alloc]init];

AVPlayerItem *model =[[AVPlayerItem alloc]initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"bhl912.mov" ofType:nil]]];

AVPlayer *player = [AVPlayer playerWithPlayerItem:model];

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

[_controller setPlayer:player];

_controller.view.frame = self.view.bounds;

_controller.videoGravity = AVLayerVideoGravityResizeAspect;

_controller.showsPlaybackControls = YES;

[self.view addSubview:_controller.view];

[_controller.player play];

方法二

- (void)playeVideo

{

MoviePlayerViewController* avPlayer = [[MoviePlayerViewController alloc] init];

[avPlayer setName:@"bhl912.mov"];

[self presentViewController:avPlayer animated:YES completion:nil];

}

#import@interface MoviePlayerViewController : AVPlayerViewController

@property(nonatomic,strong)NSString *name ;

@end

@implementation MoviePlayerViewController

-(void)setName:(NSString *)name

{

_name = name;

NSString *playString = [[NSBundle mainBundle] pathForResource:name ofType:nil];

//视频播放的url

NSURL *playerURL = [NSURL fileURLWithPath:playString];

self.player = [[AVPlayer alloc] initWithURL:playerURL];

self.videoGravity = AVLayerVideoGravityResizeAspect;

}

- (void)viewDidLoad {

[super viewDidLoad];

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dismiss) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

// Do any additional setup after loading the view.

}

-(void)dismiss

{

[self dismissViewControllerAnimated:YES completion:nil];

}

-(void)viewDidAppear:(BOOL)animated

{

[super viewDidAppear: animated];

[self.player play];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

-(void)dealloc

{

[[NSNotificationCenter defaultCenter]removeObserver:self];

}

上一篇 下一篇

猜你喜欢

热点阅读