版本记录
版本号 | 时间 |
---|---|
V1.0 | 2017.12.26 |
前言
ios系统中有很多方式可以播放音频文件,这里我们就详细的说明下播放音乐文件的原理和实例。感兴趣的可以看我写的上面几篇。
1. 几种播放音频文件的方式(一) —— 播放本地音乐
2. 几种播放音频文件的方式(二) —— 音效播放
功能要求
播放网络音乐
功能实现
1. 模块说明
下面我们就分模块进行说明
创建AVPlayerItem
- (AVPlayerItem *)getItemWithIndex:(NSInteger)index
{
NSURL *url = [NSURL URLWithString:self.musicArray[index]];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
//KVO监听播放状态
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//KVO监听缓存大小
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//通知监听item播放完毕
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playOver:) name:AVPlayerItemDidPlayToEndTimeNotification object:item];
return item;
}
实现KVO的方法,根据keyPath来判断观察的属性
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
AVPlayerItem *item = object;
if ([keyPath isEqualToString:@"status"]) {
switch (self.player.status) {
case AVPlayerStatusUnknown:
NSLog(@"未知状态,不能播放");
break;
case AVPlayerStatusReadyToPlay:
NSLog(@"准备完毕,可以播放");
break;
case AVPlayerStatusFailed:
NSLog(@"加载失败, 网络相关问题");
break;
default:
break;
}
}
if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
NSArray *array = item.loadedTimeRanges;
//本次缓存的时间
CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];
NSTimeInterval totalBufferTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration); //缓存的总长度
self.bufferProgress.progress = totalBufferTime / CMTimeGetSeconds(item.duration);
}
}
加载AVPlayer
- (AVPlayer *)player
{
if (!_player) {
// 根据链接数组获取第一个播放的item, 用这个item来初始化AVPlayer
AVPlayerItem *item = [self getItemWithIndex:self.currentIndex];
// 初始化AVPlayer
_player = [[AVPlayer alloc] initWithPlayerItem:item];
__weak typeof(self)weakSelf = self;
// 监听播放的进度的方法,addPeriodicTime: ObserverForInterval: usingBlock:
/*
DMTime 每到一定的时间会回调一次,包括开始和结束播放
block回调,用来获取当前播放时长
return 返回一个观察对象,当播放完毕时需要,移除这个观察
*/
_timeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
float current = CMTimeGetSeconds(time);
if (current) {
[weakSelf.progressView setProgress:current / CMTimeGetSeconds(item.duration) animated:YES];
weakSelf.progressSlide.value = current / CMTimeGetSeconds(item.duration);
}
}];
}
return _player;
}
播放和暂停
//播放
[self.player play];
//暂停
[self.player pause];
下一首和上一首
- (IBAction)next:(UIButton *)sender
{
[self removeObserver];
self.currentIndex ++;
if (self.currentIndex >= self.musicArray.count) {
self.currentIndex = 0;
}
// 这个方法是用一个item取代当前的item
[self.player replaceCurrentItemWithPlayerItem:[self getItemWithIndex:self.currentIndex]];
[self.player play];
}
- (IBAction)last:(UIButton *)sender
{
[self removeObserver];
self.currentIndex --;
if (self.currentIndex < 0) {
self.currentIndex = 0;
}
// 这个方法是用一个item取代当前的item
[self.player replaceCurrentItemWithPlayerItem:[self getItemWithIndex:self.currentIndex]];
[self.player play];
}
// 在播放另一个时,要移除当前item的观察者,还要移除item播放完成的通知
- (void)removeObserver
{
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
[self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
控制播放进度
如果不是太精确,用- (void)seekToTime:(CMTime)time:
这个方法就行,如果要精确的用这个- (void)seekToTime:(CMTime)time toleranceBefore:(CMTime)toleranceBefore toleranceAfter:(CMTime)toleranceAfter
。
if (self.player.status == AVPlayerStatusReadyToPlay) {
[self.player seekToTime:CMTimeMake(CMTimeGetSeconds(self.player.currentItem.duration) * sender.value, 1)];
}
下面我们就看一下这两个方法的API
/*!
@method seekToTime:
@abstract Moves the playback cursor.
@param time
@discussion Use this method to seek to a specified time for the current player item.
The time seeked to may differ from the specified time for efficiency. For sample accurate seeking see seekToTime:toleranceBefore:toleranceAfter:.
*/
- (void)seekToTime:(CMTime)time;
/*!
@method seekToTime:toleranceBefore:toleranceAfter:
@abstract Moves the playback cursor within a specified time bound.
@param time
@param toleranceBefore
@param toleranceAfter
@discussion Use this method to seek to a specified time for the current player item.
The time seeked to will be within the range [time-toleranceBefore, time+toleranceAfter] and may differ from the specified time for efficiency.
Pass kCMTimeZero for both toleranceBefore and toleranceAfter to request sample accurate seeking which may incur additional decoding delay.
Messaging this method with beforeTolerance:kCMTimePositiveInfinity and afterTolerance:kCMTimePositiveInfinity is the same as messaging seekToTime: directly.
*/
- (void)seekToTime:(CMTime)time toleranceBefore:(CMTime)toleranceBefore toleranceAfter:(CMTime)toleranceAfter;
2. 代码实现
下面我们就看一下代码实现。
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) UISlider *progressSlide;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIImageView *animatedView;
@property (nonatomic, strong) id timeObserver;
@end
@implementation ViewController
#pragma mark - Override Base Function
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//UI界面
[self initUI];
//可播放可录音,更可以后台播放,还可以在其他程序播放的情况下暂停播放
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
error:nil];
}
- (void)dealloc
{
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
[self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
}
if (self.timeObserver) {
[self.player removeTimeObserver:self.timeObserver];
self.timeObserver = nil;
}
}
#pragma mark - Object Private Function
- (void)initUI
{
//背景图案
self.animatedView = [[UIImageView alloc] init];
self.animatedView.image = [UIImage imageNamed:@"backView"];
self.animatedView.frame = CGRectMake((self.view.bounds.size.width - 200.0) * 0.5, (self.view.bounds.size.height - 200.0) * 0.5, 200.0, 200.0);
self.animatedView.layer.cornerRadius = 100.0;
self.animatedView.layer.masksToBounds = YES;
[self.view addSubview:self.animatedView];
//开始按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake((self.view.bounds.size.width - 200.0) * 0.5, (self.view.bounds.size.height - 200.0) * 0.5, 200.0, 200.0);
button.layer.cornerRadius = 100.0;
button.layer.masksToBounds = YES;
[button setTitle:@"开始播放" forState:UIControlStateNormal];
[button setTitle:@"停止播放" forState:UIControlStateSelected];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[button addTarget:self action:@selector(playButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
self.button = button;
//滑动条
UISlider *progressSlide = [[UISlider alloc] initWithFrame:CGRectMake(30.0, self.view.bounds.size.height - 100.0, self.view.bounds.size.width - 60.0, 50.0)];
progressSlide.backgroundColor = [UIColor purpleColor];
[progressSlide addTarget:self action:@selector(sliderDidSlide:) forControlEvents:UIControlEventValueChanged];
self.progressSlide = progressSlide;
[self.view addSubview:progressSlide];
}
- (void)playMusic
{
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
[self.player play];
}
- (void)stopMusic
{
[self.player pause];
}
- (AVPlayerItem *)getItemWithIndex:(NSInteger)index
{
//这里是用本地数据模拟网络数据,网络资源不好找
// NSString *str = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"m4a"];
NSString *str = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:str];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
//KVO监听播放状态
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//KVO监听缓存大小
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//通知监听item播放完毕
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic) name:AVPlayerItemDidPlayToEndTimeNotification object:item];
return item;
}
#pragma mark - Action && Notification
- (void)playButtonDidClick:(UIButton *)button
{
button.selected = !button.selected;
if (button.selected) {
[self playMusic];
}
else {
[self stopMusic];
self.player = nil;
if (_timer) {
[_timer invalidate];
_timer = nil;
}
self.animatedView.transform = CGAffineTransformMakeRotation(0.0);
self.progressSlide.value = 0.0;
}
}
- (void)sliderDidSlide:(UISlider *)slider
{
NSLog(@"拖动");
if (self.player.status == AVPlayerStatusReadyToPlay) {
[self.player seekToTime:CMTimeMake(CMTimeGetSeconds(self.player.currentItem.duration) * slider.value, 1)];
}
}
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
AVPlayerItem *item = object;
//状态的监听
if ([keyPath isEqualToString:@"status"]) {
switch (self.player.status) {
case AVPlayerStatusUnknown:
NSLog(@"未知状态,不能播放");
break;
case AVPlayerStatusReadyToPlay:
NSLog(@"准备完毕,可以播放");
break;
case AVPlayerStatusFailed:
NSLog(@"加载失败, 网络相关问题");
break;
default:
break;
}
}
//下载时长,获取缓冲时间
if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
NSArray *array = item.loadedTimeRanges;
//本次缓存的时间
CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];
NSTimeInterval totalBufferTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration);
//这里,获取的是缓存的总长度,我这里是本地音乐模拟网络音乐,所以这里totalBufferTime一直就是总时长
NSLog(@"totalBufferTime = %lf", totalBufferTime);
}
}
#pragma mark - Lazy load
- (AVPlayer *)player
{
if (!_player) {
//根据链接数组获取第一个播放的item, 用这个item来初始化AVPlayer
AVPlayerItem *item = [self getItemWithIndex:self.currentIndex];
//初始化AVPlayer
_player = [[AVPlayer alloc] initWithPlayerItem:item];
//监听播放的进度的方法,addPeriodicTime: ObserverForInterval: usingBlock:
/*
CMTime 每到一定的时间会回调一次,包括开始和结束播放
block回调,用来获取当前播放时长
return 返回一个观察对象,当播放完毕时需要,移除这个观察
*/
__weak typeof(self) weakSelf = self;
self.timeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
float current = CMTimeGetSeconds(time);
NSLog(@"时间 = %lf - duration = %lf", current, CMTimeGetSeconds(item.duration));
if (current) {
weakSelf.progressSlide.value = current / CMTimeGetSeconds(item.duration);
}
}];
}
return _player;
}
- (NSTimer *)timer
{
__weak typeof(self) weakSelf = self;
_timer = [NSTimer timerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
weakSelf.animatedView.transform = CGAffineTransformRotate(weakSelf.animatedView.transform, M_PI * 0.1);
}];
return _timer;
}
@end
功能效果
这里声音就不能给大家展示了,但是可以给大家展示界面,具体可以用代码自己运行。
下面看输出结果
2017-12-26 23:38:21.912444+0800 JJMusic_demo2[29647:5084586] 时间 = 0.000000 - duration = nan
2017-12-26 23:38:21.913116+0800 JJMusic_demo2[29647:5084586] 时间 = 0.000000 - duration = nan
2017-12-26 23:38:21.922656+0800 JJMusic_demo2[29647:5084586] 时间 = 0.000000 - duration = nan
2017-12-26 23:38:21.948784+0800 JJMusic_demo2[29647:5084586] totalBufferTime = 249.364898
2017-12-26 23:38:21.951430+0800 JJMusic_demo2[29647:5084586] 准备完毕,可以播放
2017-12-26 23:38:22.110312+0800 JJMusic_demo2[29647:5084586] 时间 = 0.000000 - duration = 249.364898
2017-12-26 23:38:22.110775+0800 JJMusic_demo2[29647:5084586] 时间 = 0.000000 - duration = 249.364898
2017-12-26 23:38:22.608319+0800 JJMusic_demo2[29647:5084586] totalBufferTime = 249.364898
2017-12-26 23:38:23.147871+0800 JJMusic_demo2[29647:5084586] 时间 = 1.001264 - duration = 249.364898
2017-12-26 23:38:24.147846+0800 JJMusic_demo2[29647:5084586] 时间 = 2.001185 - duration = 249.364898
2017-12-26 23:38:25.147776+0800 JJMusic_demo2[29647:5084586] 时间 = 3.001157 - duration = 249.364898
2017-12-26 23:38:26.147997+0800 JJMusic_demo2[29647:5084586] 时间 = 4.001191 - duration = 249.364898
2017-12-26 23:38:27.147628+0800 JJMusic_demo2[29647:5084586] 时间 = 5.001153 - duration = 249.364898
2017-12-26 23:38:28.147630+0800 JJMusic_demo2[29647:5084586] 时间 = 6.001168 - duration = 249.364898
2017-12-26 23:38:29.147603+0800 JJMusic_demo2[29647:5084586] 时间 = 7.001173 - duration = 249.364898
2017-12-26 23:38:30.147581+0800 JJMusic_demo2[29647:5084586] 时间 = 8.001196 - duration = 249.364898
2017-12-26 23:38:31.147527+0800 JJMusic_demo2[29647:5084586] 时间 = 9.001166 - duration = 249.364898
2017-12-26 23:38:32.147437+0800 JJMusic_demo2[29647:5084586] 时间 = 10.001151 - duration = 249.364898
2017-12-26 23:38:33.147451+0800 JJMusic_demo2[29647:5084586] 时间 = 11.001168 - duration = 249.364898
2017-12-26 23:38:34.147956+0800 JJMusic_demo2[29647:5084586] 时间 = 12.001356 - duration = 249.364898
后记
未完,待续~~~