AVPlayer

<span style="font-size:18px;">写了备注  就上传上来了,没什么东西。</span>

//
//  ViewController.m
//  MyPlayerDemo
//
//  Created by JackYang on 15/9/22.
//  Copyright (c) 2015年 JackYang. All rights reserved.
//

#import "ViewController.h"
#import "VideoPlayView.h"
#import <AVFoundation/AVFoundation.h>

#define VIDEO_URL @"http://pl.youku.com/playlist/m3u8?vid=335318814&type=flv&ts=1442884618&keyframe=0&ep=cSaQGEGFUsgB7SXajD8bZCTic35aXP0J8xyEidpjBNQnS%2By6&sid=34428846186541238079e&token=3345&ctype=12&ev=1&oip=1760889091"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet VideoPlayView *playView;
@property (weak, nonatomic) IBOutlet UISlider *slider;

//播放器,由他执行实际的播放
@property(nonatomic)AVPlayer *player;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.slider.minimumValue = 0.0;
    self.slider.maximumValue = 1.0;
    self.slider.value        = 0.0;
}
- (IBAction)progressChanged:(id)sender {
    //当前的进度百分比
    float progress = self.slider.value;
    CMTime totalTime = self.player.currentItem.duration;
    
    //CMTimeMultiplyByFloat64 把一个CMTime值乘以一个浮点数
    [self.player seekToTime:CMTimeMultiplyByFloat64(totalTime, progress)];
}

- (IBAction)play:(id)sender {
    if(self.player != nil){
        //对于处于播放状态的播放器,再次调用play无影响
        [self.player play];
        return;
    }
    
    NSString *videoPath = [[NSBundle mainBundle]pathForResource:@"1" ofType:@"mp4"];
    
    //AVURLAsset 代表一个播放的资源,可以使音频,可以是视频,可以是本地的,也可以是网络的
    //加载本地资源[NSURL fileURLWithPath:videoPath]
    AVURLAsset *localAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:videoPath]];

    //加载网络资源用[NSURL URLWithString:VIDEO_URL]
    AVURLAsset *netAsset = [AVURLAsset assetWithURL:[NSURL URLWithString:VIDEO_URL]];
    
    //AVPlayerItem 是对资源的整体描述,可以获取资源的状态,可以得到资源长度等信心,使用AVURLAsset进行初始化
    AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithAsset:netAsset];
    
    //生成播放器,使用AVPlayerItem进行初始化的时候,会对资源进行预加载分析
    //这个过程会修改playerItem的状态
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    
    //图像显示,需要播放器和layer关联起来
    [self.playView setPlayer:self.player];
    
    //使用kvo来检测playerItem 的状态信息,只有当状态变为ReadToPlay才可以播放资源
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    //关注播放结束的通知,关注通知AVPlayerItemDidPlayToEndTimeNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    __weak typeof(self) weakSelf = self;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *playerItem = (AVPlayerItem*)object;
        if( playerItem.status == AVPlayerItemStatusReadyToPlay )
        {
            //资源已经准备好播放
            [self.player play];
            
            //AVPlayer 提供了一种可以让我们周期性调用的一个block,在该block内我们可以实现进度的更新
            //AVPlayer 使用CMTime表示时间,不直接使用秒数,是考虑到播放的速率
            //value/timescale = seconds.
            //CMTime(1,1);  均可以表示1秒,但是播放速率不一样
            //CMTime(2,2);
            [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                //block中的time代表当前的播放时间
                
                //通过player.currentItem.duration 得到当前的总时长
                CMTime totalTime = weakSelf.player.currentItem.duration;
                //time/totalTime
                //CMTimeGetSeconds 把CMTime转化为秒数
               Float64 currentSeconds = CMTimeGetSeconds(time);
               Float64 totalSeconds = CMTimeGetSeconds(totalTime);
               float progress = currentSeconds*1.0/totalSeconds;
               weakSelf.slider.value = progress;
            }];
        }else{
            NSLog(@"资源不能播放");
        }
    }
}

- (void)playEnd:(NSNotification*)notify
{
    NSLog(@"检测到播放结束");
}

- (IBAction)pause:(id)sender {
    [self.player pause];
}

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAll;
}

- (void)stopPlay
{
    //先移除观察者
    [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    //暂停
    [self.player pause];
    //释放掉self.player
    self.player = nil;
}

//屏幕旋转调用的方法
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    //UIInterfaceOrientationIsLandscape 判断是否为横屏模式
    if(UIInterfaceOrientationIsLandscape(fromInterfaceOrientation))
    {
        //竖屏模式
        self.playView.frame = CGRectMake(0, 30, 375, 225);
        AVPlayerLayer *layer = (AVPlayerLayer*)self.playView.layer;
        layer.videoGravity = AVLayerVideoGravityResizeAspect;
    }else{
        //横评模式
        self.playView.frame = CGRectMake(0, 0, 667, 375);
        AVPlayerLayer *layer = (AVPlayerLayer*)self.playView.layer;
        layer.videoGravity = AVLayerVideoGravityResizeAspect;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值