iOS编程——AVPlayer解决闪屏问题

问题终于解决,选用AVPlayer,重置一下AVPlayerItem就不会出现闪屏现象,注册一个通知同样可以实现循环播放,而且AVPlayer可以自定义播放样式,给了我们更大的发挥空间,完全可以自己DIY播放器样式。并且AVPlayer完全可以实现两个视频窗口播放!

1.需要引入两个类库:

在.h中引入

#import <AVFoundation/AVFoundation.h>

在.m中引入

#import <CoreMedia/CoreMedia.h>


代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightBtn.frame = CGRectMake(50, 420, 180, 50);
    [rightBtn addTarget:self action:@selector(doRight) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"同时播放" forState:UIControlStateNormal];
    [self.view addSubview:rightBtn];
    
    
    
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"找朋友" ofType:@"mp4"];
    NSURL *sourceMovieURL = [NSURL fileURLWithPath:filePath];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    AVPlayerItem * playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    self.player_0 = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player_0];
    playerLayer.frame = CGRectMake(0, 0, 400, 500);
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:playerLayer];
    
    [_player_0 play];
    
    //注册通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(runLoopTheMovie:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    
    
}



- (void)doRight
{

    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"字母歌" ofType:@"mp4"];
    NSURL *sourceMovieURL = [NSURL fileURLWithPath:filePath];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    self.player_1 = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer * playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player_1];
     playerLayer.frame = CGRectMake(420, 0, 400, 500);
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:playerLayer];
    
    [_player_1 play];
        
}

- (void)runLoopTheMovie:(NSNotification *)n{
    //注册的通知  可以自动把 AVPlayerItem 对象传过来,只要接收一下就OK
    
    AVPlayerItem * p = [n object];
    //关键代码 
    [p seekToTime:kCMTimeZero];
    
    [_player_0 play];
    NSLog(@"重播");
}

Demo链接:http://download.csdn.net/detail/u012405234/6614853

运行环境:Xcode 4.6.3 ARC


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值