美文网首页
iOS在线播放视频 AVPlayer (简单就好)

iOS在线播放视频 AVPlayer (简单就好)

作者: 陪你宿醉的人注定无法送你回家 | 来源:发表于2019-01-25 15:09 被阅读0次

    .h文件
    //第一步:引用AVFoundation框架,添加播放器属性 声明对象

    #import   <AVFoundation/AVFoundation.h>

    //创建对象

    @property (nonatomic,strong)AVPlayer *player;//播放器对象

    @property (nonatomic, strong) AVPlayerLayer *playerLayer;

    @property (nonatomic,strong)AVPlayerItem *currentPlayerItem;

    @property (nonatomic,strong)UIView *containerView;

    .m

     // 2.创建AVPlayerItem

        _currentPlayerItem = [AVPlayerItem playerItemWithURL:url];

        //通过KVO来观察status属性的变化,来获得播放之前的错误信息

        [_currentPlayerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];

    context:nil];

        // 3.创建AVPlayer

        _player = [AVPlayer playerWithPlayerItem:_currentPlayerItem];

     // 4.添加AVPlayerLayer

        _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];

          self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;

        self.playerLayer.frame = CGRectMake( 0, 104, self.view.frame.size.width, self.view.frame.size.height/2.2);

        self.playerLayer.videoGravity = AVLayerVideoGravityResize;

        [self.view.layer addSublayer:self.playerLayer];

    //此处可以直接播放但是建议在监听方法中播放

    // [_playerplay];

    //监听状态回调方法

    - (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:

    (NSDictionary *)change context:(void*)context

        if([keyPathisEqualToString:@"status"]) {

            //取出status的新值

            AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey]intValue];

            switch(status) {

                case AVPlayerItemStatusFailed:

    //失败 做相关失败操作

                    break;

                case AVPlayerItemStatusReadyToPlay:

    //成功开始播放

                    [_playerplay];

                    break;

                case AVPlayerItemStatusUnknown:

                    NSLog(@"视频资源出现未知错误");

                    break;

                default:

                    break;

            }

        }

        //移除监听(观察者)

        [objectremoveObserver:self forKeyPath:@"status"];

    }

    相关文章

      网友评论

          本文标题:iOS在线播放视频 AVPlayer (简单就好)

          本文链接:https://www.haomeiwen.com/subject/ddnmjqtx.html