AVPlayer播放视频

//

//  ViewController.m

//  04-AVPlayer播放视频

//

//  Created by鹿微微鹿 on 16/5/6.

//  Copyright (c) 2016 鹿微微鹿. All rights reserved.

//


#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

{

    //播放器

    AVPlayer *_player;

    //显示画面的Layer

    AVPlayerLayer *imageLayer;

    

    UIProgressView *progress;

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    NSString *path =

        @"http://otmv.alicdn.com/new/mv_1_6/23/77/2306cd13e3dde338b53f404ece43a277.mp4?k=7125c1a8f09b70bb&t=1451830866";

    

    //1.创建item

    AVPlayerItem *item = [[AVPlayerItem alloc]

                          initWithURL:[NSURL URLWithString:path]];

    

    //2.创建播放器对象

    _player = [AVPlayer playerWithPlayerItem:item];

    

    

    //3.播放

    [_player play];


    //==================显示图像========================

    //4.创建显示视频的layer专门用来显示视频图像的

    //参数:播放器

   imageLayer   = [AVPlayerLayer playerLayerWithPlayer:

                                 _player];

    

    //2.设置frame

    imageLayer.frame = self.view.bounds;


    //3.添加到界面上

    [self.view.layer addSublayer:imageLayer];

    

    //4.获取视频界面的大小

    CGRect rect = imageLayer.videoRect;

    

   

    

    

    //=========屏幕旋转==================


    [[NSNotificationCenter defaultCenter]

     addObserver:self selector:@selector(screenChangeSite) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];

    

}


- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

     CGRect rect = imageLayer.videoRect;

    //5.创建一个进度条

    progress = [[UIProgressView alloc]

                initWithFrame:CGRectMake(rect.origin.x,rect.origin.y+rect.size.height, rect.size.width, 10)];

    [self.view addSubview:progress];

      __weak UIProgressView *p = progress;

    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1,10 ) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {

      

        //更新进度

        //总时间

      float total =  _player.currentItem.duration.value / _player.currentItem.duration.timescale;

        //当前时间

        float current = time.value * 1.0f/time.timescale;

        

        p.progress = current/total;

        

    }];

    

    //显示样式

    //AVLayerVideoGravityResizeAspect 默认的,没有缩放

    //AVLayerVideoGravityResize:layer有多大就显示多大视频有缩放

    //AVLayerVideoGravityResizeAspectFill 按比例缩放,显示不全

    [imageLayer setVideoGravity:AVLayerVideoGravityResizeAspect];

    

    

}


#pragma mark - 屏幕旋转frame改变

- (void)screenChangeSite{

    

    NSLog(@"屏幕旋转");

    imageLayer.frame = self.view.bounds;

     CGRect rect = imageLayer.videoRect;

    progress.frame = CGRectMake(rect.origin.x,rect.origin.y+rect.size.height, rect.size.width, 10);

}


@end





























你可能感兴趣的:(视频播放)