iOS之AVPlayer的简单应用

//
//  ViewController.m
//  avplayertest
//
//  Created by 11 on 2019/7/19.
//

#import "ViewController.h"
#import 
#import 

#define VIDEOURL @"your_video_url"

@interface ViewController ()

@property (nonatomic,strong)AVPlayer * player;
@property (nonatomic,strong)AVPlayerItem * playItem;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL * videoUrl = [NSURL URLWithString:VIDEOURL];
    
    // 设置播放项目
    self.playItem = [[AVPlayerItem alloc] initWithURL:videoUrl];
    // 初始化player对象
    self.player = [[AVPlayer alloc] initWithPlayerItem:self.playItem];
    // 设置播放页面
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    [self.playItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    layer.frame = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 300);
    // 添加到当前页
    [self.view.layer addSublayer:layer];
    
    
    __weak ViewController *weakSelf = self;
    // 获取当前播放时间,可以用value/timescale的方式
    CMTime interval = CMTimeMakeWithSeconds(1, NSEC_PER_SEC);
    [self.player addPeriodicTimeObserverForInterval:interval queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        float currentTime = weakSelf.playItem.currentTime.value/weakSelf.playItem.currentTime.timescale;
        NSLog(@"%f",currentTime);
        
        // 获取视频总时间
        float totalTime = CMTimeGetSeconds(weakSelf.playItem.duration);
        NSLog(@"%f",totalTime);
    }];
    
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([object isKindOfClass:[AVPlayerItem class]]) {
        if ([keyPath isEqualToString:@"status"]) {
            switch (self.playItem.status) {
                case AVPlayerItemStatusReadyToPlay:
                    // 播放方法在这里,比较稳妥
                    NSLog(@"准备播放");
                    [self.player play];
                    break;
                case AVPlayerItemStatusFailed:
                    NSLog(@"准备失败");
                    break;
                case AVPlayerItemStatusUnknown:
                    NSLog(@"未知");
                    break;
                    
                default:
                    break;
            }
        }
    }
    
    
}


@end

https://www.cnblogs.com/zhun/p/5536962.html
https://www.jianshu.com/p/4a6420a9ee18

AVPlayer是一个可以播放任何格式的全功能影音播放器,支持视频、音频格式多;
不做直播功能的话,AVPlayer就是一个最优的选择。

你可能感兴趣的:(UI布局,基本控件)