视频播放

227 阅读3分钟
创建播放器(四种方法)
URL创建的方式会默认为AVPlayer创建一个AVPlayerItem
self.player = [AVPlayer playerWithURL:localVideoUrl];
self.player = [[AVPlayer alloc] initWithURL:localVideoUrl];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
#import "ViewController.h"
#import <AVKit/AVKit.h>


@interface ViewController ()

@property (nonatomic,strong) AVPlayerItem *item;
@property (nonatomic,strong) AVPlayerLayer *playerLayer;
@property (nonatomic,strong) AVPlayer *myPlayer;
@property (strong, nonatomic) UISlider *avSlider;//用来现实视频的播放进度,并且通过它来控制视频的快进快退。
@property (assign, nonatomic) BOOL isReadToPlay;//用来判断当前视频是否准备好播放。

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self avPlayerMethod];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(250, 600, 100, 100);
    button.backgroundColor = [UIColor redColor];
    [button setTitle:@"按钮" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    [self.avSlider addTarget:self action:@selector(avSliderAction) forControlEvents:
     UIControlEventTouchUpInside|UIControlEventTouchCancel|UIControlEventTouchUpOutside];
}

- (void)avPlayerMethod {
    //构建播放网址
    NSURL *mediaURL = [NSURL URLWithString:@"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
    //构建播放单元
    self.item = [AVPlayerItem playerItemWithURL:mediaURL];
    //构建播放器对象
    self.myPlayer = [AVPlayer playerWithPlayerItem:self.item];
    //构建播放器的layer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.myPlayer];
    self.playerLayer.frame = CGRectMake(0, 66, self.view.bounds.size.width, 300);
    [self.view.layer addSublayer:self.playerLayer];
    //通过KVO来观察status属性的变化,来获得播放之前的错误信息
    [self.item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:
(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        //取出status的新值
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey]intValue];
        switch (status) {
            case AVPlayerItemStatusFailed:
                NSLog(@"item 有误");
                self.isReadToPlay = NO;
                break;
            case AVPlayerItemStatusReadyToPlay:
                NSLog(@"准好播放了");
                self.isReadToPlay = YES;
                self.avSlider.maximumValue = self.item.duration.value / self.item.duration.timescale;
                break;
            case AVPlayerItemStatusUnknown:
                NSLog(@"视频资源出现未知错误");
                self.isReadToPlay = NO;
                break;
            default:
                break;
        }
    }
    //移除监听(观察者)
    [object removeObserver:self forKeyPath:@"status"];
}

- (void)playAction {
    if (self.isReadToPlay) {
        [self.myPlayer play];
    }else{
        NSLog(@"视频正在加载中");
    }
}

- (UISlider *)avSlider {
    if (!_avSlider) {
        _avSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 355, self.view.bounds.size.width, 30)];
        [self.view addSubview:_avSlider];
    }
    return _avSlider;
}

- (void)avSliderAction {
    //slider的value值为视频的时间
    float seconds = self.avSlider.value;
    //让视频从指定的CMTime对象处播放。
    CMTime startTime = CMTimeMakeWithSeconds(seconds, self.item.currentTime.timescale);
    //让视频从指定处播放
    [self.myPlayer seekToTime:startTime completionHandler:^(BOOL finished) {
        if (finished) {
            [self playAction];
        }
    }];
}

@end
#import "ViewController.h"
//导入系统框架
#import <AVFoundation/AVFoundation.h>

@interface ViewController( )

@property (strong, nonatomic) AVPlayer *avPlayer;

@end

@implementation ViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"视频播放";
    
    //网络视频播放
    NSString *playString = @"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4";
    NSURL *url = [NSURL URLWithString:playString];
    
//    //本地视频播放
//    NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"霍建华、赵丽颖 - 不可说" ofType:@"mp4"];
//    NSURL *url = [NSURL fileURLWithPath:audioPath];
    
    //设置播放的项目
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
    //初始化player对象
    self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:item];
    //设置播放页面
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];
    //设置播放页面的大小
    layer.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 230);
    layer.backgroundColor = [UIColor cyanColor].CGColor;
    //设置播放窗口和当前视图之间的比例显示内容
    //1.保持纵横比;适合层范围内
    //2.保持纵横比;填充层边界
    //3.拉伸填充层边界
    /*
     第1种AVLayerVideoGravityResizeAspect是按原视频比例显示,是竖屏的就显示出竖屏的,两边留黑;
     第2种AVLayerVideoGravityResizeAspectFill是以原比例拉伸视频,直到两边屏幕都占满,但视频内容有部分就被切割了;
     第3种AVLayerVideoGravityResize是拉伸视频内容达到边框占满,但不按原比例拉伸,这里明显可以看出宽度被拉伸了。
     */
    layer.videoGravity = AVLayerVideoGravityResizeAspect;
    //添加播放视图到self.view
    [self.view.layer addSublayer:layer];
    //视频播放
    [self.avPlayer play];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //视频暂停
//    [self.avPlayer pause];
}

@end
#import "ViewController.h"
#import <AVKit/AVKit.h>

@interface ViewController ()
@property (nonatomic, strong) NSString *videoUrl;
@property (nonatomic, strong)AVPlayerViewController *playerVC;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.videoUrl =  [[NSBundle mainBundle] pathForResource:@"guideMovie1" ofType:@"mov"];
    self.videoUrl = @"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
    /*
     因为是 http 的链接,所以要去 info.plist里面设置
     App Transport Security Settings
     Allow Arbitrary Loads  = YES
     */
    self.playerVC = [[AVPlayerViewController alloc] init];
    self.playerVC.player = [AVPlayer playerWithURL:[self.videoUrl hasPrefix:@"http"] ? [NSURL URLWithString:self.videoUrl]:[NSURL fileURLWithPath:self.videoUrl]];
    self.playerVC.view.frame = self.view.bounds;
    self.playerVC.showsPlaybackControls = YES;
//self.playerVC.entersFullScreenWhenPlaybackBegins = YES;//开启这个播放的时候支持(全屏)横竖屏哦
//self.playerVC.exitsFullScreenWhenPlaybackEnds = YES;//开启这个所有 item 播放完毕可以退出全屏
    [self.view addSubview:self.playerVC.view];
    
    if (self.playerVC.readyForDisplay) {
        [self.playerVC.player play];
    }
}
@end