AVPlayer實現視頻播放

Demo

實現功能:
1.視頻的播放/暫停
2.播放進度前進後退

ViewController
import AVFoundation/AVFoundation.h
import “TQPlayView.h”

@interface ViewController ()

@property (nonatomic,strong) AVPlayer *player;

@property (nonatomic,strong) AVPlayerItem *item;

@property (nonatomic) CMTime time;

@property (weak, nonatomic) IBOutlet UISlider *proSlider;
- (IBAction)proChange:(id)sender;

  • (IBAction)start:(id)sender;

@end

//UIView —> CALayer
//AVPlayer —> layer —> AVPlayerLayer.player

//UIView

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSString *path = [[NSBundle mainBundle] pathForResource:@”3” ofType:@”mp4”];
    //
    self.item = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:path]];

    self.player = [[AVPlayer alloc] initWithPlayerItem:self.item];

    TQPlayView *playView = [[TQPlayView alloc] initWithFrame:self.view.bounds];
    //CALayer
    ((AVPlayerLayer *)playView.layer).player = self.player;
    [self.view addSubview:playView];
    [self.view sendSubviewToBack:playView];

    //
    [self.item addObserver:self forKeyPath:@”status” options:NSKeyValueObservingOptionNew context:nil];
    }

-(void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context
{
AVPlayerItemStatus s = [change[NSKeyValueChangeNewKey] integerValue];

if(s == AVPlayerItemStatusReadyToPlay)
{
    //總時間
    //幀率  CMTime  value 總幀數  timescale  每秒播放的幀數
    self.proSlider.maximumValue = self.item.duration.value / self.item.duration.timescale;

    self.time = self.item.duration;

    //防止循環引用
    __weak UISlider *slider = self.proSlider;

    //添加一個定時   間隔時間 1
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:nil usingBlock:^(CMTime time) {
        //time 當前的播放時間
        slider.value = time.value / time.timescale;
    }];
}

}

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

  • (IBAction)proChange:(UISlider *)sender {
    //sender.value * timescale
    [self.player seekToTime:CMTimeMake(sender.value * self.time.timescale, self.time.timescale)];
    }

  • (IBAction)start:(UIButton *)sender {

    if(!sender.selected)
    {
    [self.player play];
    }
    else
    {
    [self.player pause];
    }

    sender.selected = !sender.selected;
    }

TQPlayView.m

import AVFoundation/AVFoundation.h

@implementation TQPlayView
//改變layer的類型 AVPlayerLayer
+(Class)layerClass
{
return [AVPlayerLayer class];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/

@end

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章