几种播放音频文件的方式(三) —— 网络音乐播放

版本记录

版本号 时间
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

后记

未完,待续~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容