//ide
// ViewController.matom
// 03-AVPlayerspa
//.net
// Created by 鹿微微鹿 on 16/5/6.3d
// Copyright (c) 2016年 鹿微微鹿. All rights reserved.orm
//server
//AVPlayer對象
#import "ViewController.h"隊列
#import <AVFoundation/AVFoundation.h>get
@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