//
// ViewController.m
// 03-AVPlayer
//
// Created by 鹿微微鹿 on 16/5/6.
// Copyright (c) 2016年 鹿微微鹿. All rights reserved.
//
//AVPlayer
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController (){
//播放器
AVPlayer *_player;
}
@property (weak, nonatomic) IBOutlet UISlider *sliderProgress;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1.创建播放源对象
NSString *path = [[NSBundle mainBundle]pathForResource:@"MovieTest.mp4" ofType:nil];
AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL fileURLWithPath:path]];
//2.创建播放器对象
_player = [[AVPlayer alloc]initWithPlayerItem:playerItem];
//3.播放
[_player play];
//4.暂停
//[_player pause];
//5.自动检测播放进度
//参数1:间隔时间
//参数2:block执行的队列
//参数3:每隔参数1调用的block在这个block中可以获取当前帧数和播放速度
//在block中警告的解决方法
__weak AVPlayer *tplayer =_player;
__weak UISlider *tslider = _sliderProgress;
[_player addPeriodicTimeObserverForInterval:CMTimeMake(1,10)
queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//拿到总的帧数
CMTime totalTime = tplayer.currentItem.duration;
//总的时间
float total = totalTime.value * 1.0f / totalTime.timescale;
//当前时间
float current = time.value*1.0f/time.timescale;
//设置进度条
tslider.value = current /total;
}];
//设置音量
_player.volume = 0.5;
//设置播放速度范围是0.5-2.0默认是1
_player.rate = 1.0;
//使用消息中心区检测播放结束的时刻
//AVPlayerItemDidPlayToEndTimeNotification
//
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(endPlay) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
//9.切换播放源
// [_player replaceCurrentItemWithPlayerItem:nil];
}
#pragma mark - 消息中心
- (void)endPlay{
NSLog(@"结束播放");
self.sliderProgress.value = 0;
NSString *path = [[NSBundle mainBundle]
pathForResource:@"亡灵序曲.mp3" ofType:nil];
AVPlayerItem *item = [[AVPlayerItem alloc]
initWithURL:[NSURL fileURLWithPath:path]];
//1.切换到下一首歌曲
[_player replaceCurrentItemWithPlayerItem:item];
//切换后要手动播放
[_player play];
}
#pragma mark - 按钮点击
//播放
- (IBAction)plsy:(id)sender {
[_player play];
}
//暂停
- (IBAction)pause:(id)sender {
[_player pause];
}
#pragma mark - 拖动进度条的时候音乐进度改变
- (IBAction)sliderChangeValue:(UISlider *)sender {
//CMTime是一个结构体
//value 媒体文件总的帧数
//timeScale 每一秒播放的帧数
//时间 = value / timeScale
//定位到第二秒
//[_player seekToTime:CMTimeMake(2,1)];
//定位到第十秒
//[_player seekToTime:CMTimeMake(10,1)];
//根据进度进行定位
//总时间 = 总的帧数/播放速度
//slider的进度的位置:(总的帧数*slider.value)/播放速度
//1.获取当前播放媒体总的帧数
//a.获取播放源
AVPlayerItem *current = _player.currentItem;
//b.获取到总帧数
//总帧数
CMTimeValue total = current.duration.value;
//播放速度
CMTimeScale speed = current.duration.timescale;
//设置进度
[_player seekToTime:CMTimeMake(total * sender.value,speed )];
}
#pragma mark - 步进器改变速度
- (IBAction)changeSpeed:(UIStepper *)sender {
_player.rate = sender.value;
}
@end
来源:oschina
链接:https://my.oschina.net/u/2683146/blog/671218