服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS之基于FreeStreamer的简单音乐播放器示例

iOS之基于FreeStreamer的简单音乐播放器示例

2021-04-05 16:27suiling IOS

这篇文章主要介绍了iOS之基于FreeStreamer的简单音乐播放器示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

前提准备

为了能够有明确的思路来做这个demo,我下载了qq音乐和网易云音乐,然后分别对比,最终选择了qq音乐来参照,先是获取了其中的所有资源文件(如果有不知道怎么提取资源文件的,可以参考ios提取app中的图片资源),在这之后就是研究使用技术,这里我选择了freestreamer,虽然系统也有,但是该框架可能更好用点。

实现部分

在这之前,先来看看大概效果图吧

iOS之基于FreeStreamer的简单音乐播放器示例

iOS之基于FreeStreamer的简单音乐播放器示例

iOS之基于FreeStreamer的简单音乐播放器示例

再看完效果图之后,我们就来看看这其中涉及到的几个难点吧(在我看开~)

1、先让播放器跑起来

这里我使用的是pods来管理三方库,代码如下

?
1
2
3
4
5
6
7
8
9
10
platform:ios,'8.0'
target "glmusicbox" do
pod 'freestreamer', '~> 3.7.3'
pod 'sdwebimage', '~> 4.0.0'
pod 'mjrefresh', '~> 3.1.11'
pod 'masonry', '~> 1.0.2'
pod 'reachability', '~> 3.2'
pod 'afnetworking', '~> 3.0'
pod 'iqkeyboardmanager', '~> 3.3.2'
end

针对freestreamer我简单进行了封装下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#import "fsaudiostream.h"
@class glmusiclrcmodel;
typedef ns_enum(nsinteger,glloopstate){
  glsingleloop = 0,//单曲循环
  glforeverloop,//重复循环
  glrandomloop,//随机播放
  glonceloop//列表一次顺序播放
};
@protocol glmusicplayerdelegate/**
 *
 实时更新
 *
 **/
- (void)updateprogresswithcurrentposition:(fsstreamposition)currentposition endposition:(fsstreamposition)endposition;
- (void)updatemusiclrc;
@end
@interface glmusicplayer : fsaudiostream
/**
 *
 播放列表
 *
 **/
@property (nonatomic,strong) nsmutablearray *musiclistarray;
/**
 当前播放歌曲的歌词
 */
@property (nonatomic,strong) nsmutablearray *musiclrcarray;
/**
 *
 当前播放
 *
 **/
@property (nonatomic,assign,readonly) nsuinteger currentindex;
/**
 *
 当前播放的音乐的标题
 *
 **/
@property (nonatomic,strong) nsstring *currenttitle;
/**
 是否是暂停状态
 */
@property (nonatomic,assign) bool ispause;
@property (nonatomic,weak) idglplayerdelegate;
//默认 重复循环 glforeverloop
@property (nonatomic,assign) glloopstate loopstate;
/**
 *
 单例播放器
 *
 **/
+ (instancetype)defaultplayer;
/**
 播放队列中的指定的文件
 @param index 序号
 */
- (void)playmusicatindex:(nsuinteger)index;
/**
 播放前一首
 */
- (void)playfont;
/**
 播放下一首
 */
- (void)playnext;
@end

这里继承了fsaudiostream,并且采用了单例模式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
+ (instancetype)defaultplayer
{
  static glmusicplayer *player = nil;
  static dispatch_once_t oncetoken;
  dispatch_once(&oncetoken, ^{
    fsstreamconfiguration *config = [[fsstreamconfiguration alloc] init];
    config.httpconnectionbuffersize *=2;
    config.enabletimeandpitchconversion = yes;
    
    
    player = [[super alloc] initwithconfiguration:config];
    player.delegate = (id)self;
    player.onfailure = ^(fsaudiostreamerror error, nsstring *errordescription) {
      //播放错误
      //有待解决
    };
    player.oncompletion = ^{
      //播放完成
        nslog(@" 打印信息: 播放完成1");
    };
  
    
    player.onstatechange = ^(fsaudiostreamstate state) {
      switch (state) {
        case kfsaudiostreamplaying:
        {
          nslog(@" 打印信息 playing.....");
          player.ispause = no;
          
          [glminimusicview shareinstance].palybutton.selected = yes;
        }
          break;
        case kfsaudiostreamstopped:
        {
          nslog(@" 打印信息 stop.....%@",player.url.absolutestring);
        }
          break;
        case kfsaudiostreampaused:
        {
          //pause
          player.ispause = yes;
          [glminimusicview shareinstance].palybutton.selected = no;
            nslog(@" 打印信息: pause");
        }
          break;
        case kfsaudiostreamplaybackcompleted:
        {
          nslog(@" 打印信息: 播放完成2");
          [player playmusicforstate];
        }
          break;
        default:
          break;
      }
    };
    //设置音量
    [player setvolume:0.5];
    //设置播放速率
    [player setplayrate:1];
    player.loopstate = glforeverloop;
  });
  return player;
}

然后实现了播放方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
- (void)playfromurl:(nsurl *)url
{
  //根据地址 在本地找歌词
  nsmutabledictionary *dic = [nsmutabledictionary dictionarywithcontentsoffile:[[nsbundle mainbundle] pathforresource:@"musiclist" oftype:@"plist"]];
  for (nsstring *playstringkey in dic.allkeys) {
    if ([[dic valueforkey:playstringkey] isequaltostring:url.absolutestring]) {
      self.currenttitle = playstringkey;
      break;
    }
  }
  
  [self stop];
  if (![url.absolutestring isequaltostring:self.url.absolutestring]) {
    [super playfromurl:url];
  }else{
    [self play];
  }
  
  nslog(@" 当前播放歌曲:%@",self.currenttitle);
  
  [glminimusicview shareinstance].titlelable.text = self.currenttitle;
  
  //获取歌词
  nsstring *lrcfile = [nsstring stringwithformat:@"%@.lrc",self.currenttitle];
  self.musiclrcarray = [nsmutablearray arraywitharray:[glmusiclrcmodel musiclrcmodelswithlrcfilename:lrcfile]];
  
  if (![self.musiclistarray containsobject:url]) {
    [self.musiclistarray addobject:url];
  }
  
  //更新主界面歌词ui
  if (self.glplayerdelegate && [self.glplayerdelegate respondstoselector:@selector(updatemusiclrc)])
  {
    [self.glplayerdelegate updatemusiclrc];
  }
  _currentindex = [self.musiclistarray indexofobject:url];
  
  if (!_progresstimer) {
    _progresstimer = [cadisplaylink displaylinkwithtarget:self selector:@selector(updateprogress)];
    [_progresstimer addtorunloop:[nsrunloop mainrunloop] formode:nsrunloopcommonmodes];
  }
}

在上面的代码中,有许多逻辑是后面加的,比如更新ui界面,获取歌词等处理,如果要实现简单的播放,则可以不用重写该方法,直接通过playfromurl就可以实现我们的播放功能。

2、更新ui

这里的ui暂不包括歌词的更新,而只是进度条的更新,要更新进度条,比不可少的是定时器,这里我没有选择nstimer,而是选择了cadisplaylink,至于为什么,我想大家应该都比较了解,可以这么来对比,下面引用一段其他博客的对比:

ios设备的屏幕刷新频率是固定的,cadisplaylink在正常情况下会在每次刷新结束都被调用,精确度相当高。

nstimer的精确度就显得低了点,比如nstimer的触发时间到的时候,runloop如果在阻塞状态,触发时间就会推迟到下一个runloop周期。并且 nstimer新增了tolerance属性,让用户可以设置可以容忍的触发的时间的延迟范围。

cadisplaylink使用场合相对专一,适合做ui的不停重绘,比如自定义动画引擎或者视频播放的渲染。nstimer的使用范围要广泛的多,各种需要单次或者循环定时处理的任务都可以使用。在ui相关的动画或者显示内容使用 cadisplaylink比起用nstimer的好处就是我们不需要在格外关心屏幕的刷新频率了,因为它本身就是跟屏幕刷新同步的

使用方法

?
1
2
3
4
if (!_progresstimer) {
   _progresstimer = [cadisplaylink displaylinkwithtarget:self selector:@selector(updateprogress)];
   [_progresstimer addtorunloop:[nsrunloop mainrunloop] formode:nsrunloopcommonmodes];
 }

更新进度

?
1
2
3
4
5
6
7
8
9
- (void)updateprogress
{
  if (self.glplayerdelegate && [self.glplayerdelegate respondstoselector:@selector(updateprogresswithcurrentposition:endposition:)])
  {
    [self.glplayerdelegate updateprogresswithcurrentposition:self.currenttimeplayed endposition:self.duration];
  }
  
  [self showlockscreencurrenttime:(self.currenttimeplayed.second + self.currenttimeplayed.minute * 60) totaltime:(self.duration.second + self.duration.minute * 60)];
}

在这里有两个属性:currenttimeplayed和duration,分别保存着当前播放时间和总时间,是如下的结构体

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef struct {
  unsigned minute;
  unsigned second;
  
  /**
   * playback time in seconds.
   */
  float playbacktimeinseconds;
  
  /**
   * position within the stream, where 0 is the beginning
   * and 1.0 is the end.
   */
  float position;
} fsstreamposition;

我们在更新ui的时候,主要可以根据其中的minute和second来,如果播放了90s,那么minute就为1,而second为30,所以我们在计算的时候,应该是这样的(self.currenttimeplayed.second + self.currenttimeplayed.minute * 60)

当然在更新进度条的时候,我们也可以通过position直接来给slider进行赋值,这表示当前播放的比例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma mark == glmusicplayerdelegate
- (void)updateprogresswithcurrentposition:(fsstreamposition)currentposition endposition:(fsstreamposition)endposition
{
  //更新进度条
  self.playercontrolview.slider.value = currentposition.position;
  
  self.playercontrolview.lefttimelable.text = [nsstring translationwithminutes:currentposition.minute seconds:currentposition.second];
  self.playercontrolview.righttimelable.text = [nsstring translationwithminutes:endposition.minute seconds:endposition.second];
  
  //更新歌词
  [self updatemusiclrcforrowwithcurrenttime:currentposition.position *(endposition.minute *60 + endposition.second)];
  self.playercontrolview.palymusicbutton.selected = [glmusicplayer defaultplayer].ispause;
}

本项目中,slider控件没有用系统的,而是简单的写了一个,大概如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@interface glslider : uicontrol
//进度条颜色
@property (nonatomic,strong) uicolor *progresscolor;
//缓存条颜色
@property (nonatomic,strong) uicolor *progresscachecolor;
//滑块颜色
@property (nonatomic,strong) uicolor *thumbcolor;
//设置进度值 0-1
@property (nonatomic,assign) cgfloat value;
//设置缓存进度值 0-1
@property (nonatomic,assign) cgfloat cachevalue;
@end
static cgfloat const kprogressheight = 2;
static cgfloat const kprogressleftpadding = 2;
static cgfloat const kthumbheight = 16;
@interface glslider()
//滑块 默认
@property (nonatomic,strong) calayer *thumblayer;
//进度条
@property (nonatomic,strong) calayer *progresslayer;
//缓存进度条
@property (nonatomic,strong) calayer *progresscachelayer;
@property (nonatomic,assign) bool istouch;
@end
@implementation glslider
- (id)initwithframe:(cgrect)frame
{
  self = [super initwithframe:frame];
  if (self) {
    [self addsublayers];
  }
  return self;
}
....

这里是添加了缓存进度条的,但是由于时间关系,代码中还未实时更新缓存进度

3、更新歌词界面

说到歌词界面,我们看到qq音乐的效果是这样的,逐行逐字进行更新,注意不是逐行更新。考虑到逐字进行更新,那么我们必须要对lable进行干点什么,这里对其进行了继承,并添加了些方法

?
1
2
3
4
@interface glmusiclrclable : uilabel
//进度
@property (nonatomic,assign) cgfloat progress;
@end
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#import "glmusiclrclable.h"
@implementation glmusiclrclable
- (void)setprogress:(cgfloat)progress
{
  _progress = progress;
  //重绘
  [self setneedsdisplay];
}
- (void)drawrect:(cgrect)rect
{
  [super drawrect:rect];
  
  cgrect fillrect = cgrectmake(0, 0, self.bounds.size.width * _progress, self.bounds.size.height);
  
  [uicolor_from_rgb(45, 185, 105) set];
  
  uirectfillusingblendmode(fillrect, kcgblendmodesourcein);
}
@end

注意uirectfillusingblendmode该方法能够实现逐字进行渐变的效果

逐字的问题解决了,那么就剩下逐行问题了,逐行的问题应该不难,是的。我们只需要在指定的时间内将其滚动就行,如下

 

复制代码 代码如下:

[self.lrctableview scrolltorowatindexpath:currentindexpath atscrollposition:uitableviewscrollpositionmiddle animated:yes]

 

但是这中要注意一个问题,那就是必须做到,在下一行进行展示的时候,取消上一行的效果,如下

?
1
2
3
4
//设置当前行的状态
[currentcell reloadcellforselect:yes];
//取消上一行的选中状态
[previouscell reloadcellforselect:no];
?
1
2
3
4
5
6
7
8
9
- (void)reloadcellforselect:(bool)select
{
  if (select) {
    _lrclable.font = [uifont systemfontofsize:17];
  }else{
    _lrclable.font = [uifont systemfontofsize:14];
    _lrclable.progress = 0;
  }
}

其中_lrclable.progress = 0;必须要,否则我们的文字颜色不会改变

在大问题已经解决的情况下,我们就需要关心另一个重要的问题了,那就是歌词。这里先介绍一个网站,可以获取歌曲名和歌词的

(找了好久....) 歌曲歌词获取 ,不过好多好听的歌曲居然播放不了,你懂得,大天朝版权问题....找一首歌,播放就能看到看到歌词了。关于歌词,有许多格式,这里我用的是lrc格式,应该还算比较主流,格式大概如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[ti:老人与海]
[ar:海鸣威 ]
[al:单曲]
[by:www.5nd.com from 那时花开]
[00:04.08]老人与海 海鸣威
[00:08.78]海鸣威
[00:37.06]秋天的夜凋零在漫天落叶里面
[00:42.43]泛黄世界一点一点随风而渐远
[00:47.58]冬天的雪白色了你我的情人节
[00:53.24]消失不见 爱的碎片
[00:57.87]rap:
[00:59.32]翻开尘封的相片
[01:00.87]想起和你看过 的那些老旧默片
[01:02.50]老人与海的情节
[01:04.23]画面中你却依稀 在浮现

在有了格式后,我们就需要一个模型,来分离歌曲信息了,下面是我建的模型

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#import @interface glmusiclrcmodel : nsobject
//该段歌词对应的时间
@property (nonatomic,assign) nstimeinterval time;
//歌词
@property (nonatomic,strong) nsstring *title;
/**
 *
 将特点的歌词格式进行转换
 *
 **/
+ (id)musiclrcwithstring:(nsstring *)string;
/**
 *
 根据歌词的路径返回歌词模型数组
 *
 **/
+ (nsarray *)musiclrcmodelswithlrcfilename:(nsstring *)name;
@end
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#import "glmusiclrcmodel.h"
@implementation glmusiclrcmodel
+(id)musiclrcwithstring:(nsstring *)string
{
  glmusiclrcmodel *model = [[glmusiclrcmodel alloc] init];
  nsarray *lrclines =[string componentsseparatedbystring:@"]"];
  if (lrclines.count == 2) {
    model.title = lrclines[1];
    nsstring *timestring = lrclines[0];
    timestring = [timestring stringbyreplacingoccurrencesofstring:@"[" withstring:@""];
    timestring = [timestring stringbyreplacingoccurrencesofstring:@"]" withstring:@""];
    nsarray *times = [timestring componentsseparatedbystring:@":"];
    if (times.count == 2) {
      nstimeinterval time = [times[0] integervalue]*60 + [times[1] floatvalue];
      model.time = time;
    }
  }else if(lrclines.count == 1){
    
  }
  
  return model;
}
+(nsarray *)musiclrcmodelswithlrcfilename:(nsstring *)name
{
  nsstring *lrcpath = [[nsbundle mainbundle] pathforresource:name oftype:nil];
  nsstring *lrcstring = [nsstring stringwithcontentsoffile:lrcpath encoding:nsutf8stringencoding error:nil];
  nsarray *lrclines = [lrcstring componentsseparatedbystring:@"\n"];
  nsmutablearray *lrcmodels = [nsmutablearray array];
  for (nsstring *lrclinestring in lrclines) {
    if ([lrclinestring hasprefix:@"[ti"] || [lrclinestring hasprefix:@"[ar"] || [lrclinestring hasprefix:@"[al"] || ![lrclinestring hasprefix:@"["]) {
      continue;
    }
    glmusiclrcmodel *lrcmodel = [glmusiclrcmodel musiclrcwithstring:lrclinestring];
    [lrcmodels addobject:lrcmodel];
  }
  return lrcmodels;
}
@end

在歌词模型准备好之后,我们要展示歌词,这里我选择的是tableview,通过每一个cell来加载不同的歌词,然后通过歌词的时间信息来更新和滚动

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma mark == uitableviewdatasource
- (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section
{
  return [glmusicplayer defaultplayer].musiclrcarray.count;
}
- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath
{
  musiclrctableviewcell *cell = [tableview dequeuereusablecellwithidentifier:@"musiclrc" forindexpath:indexpath];
  cell.selectionstyle = uitableviewcellselectionstylenone;
  cell.backgroundcolor = [uicolor clearcolor];
  cell.contentview.backgroundcolor = [uicolor clearcolor];
  
  cell.lrcmodel = [glmusicplayer defaultplayer].musiclrcarray[indexpath.row];
  
  if (indexpath.row == self.currentlcrindex) {
    [cell reloadcellforselect:yes];
  }else{
    [cell reloadcellforselect:no];
  }
  
  return cell;
}

这里面唯一比较麻烦的可能就是更新歌词了,在上面的定时器中,我们也通过代理来更新了进度条,所以我也将更新歌词的部分放在了代理中,这样可以达到实时更新的目的,下面看看方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//逐行更新歌词
- (void)updatemusiclrcforrowwithcurrenttime:(nstimeinterval)currenttime
{
  for (int i = 0; i < [glmusicplayer defaultplayer].musiclrcarray.count; i ++) {
    glmusiclrcmodel *model = [glmusicplayer defaultplayer].musiclrcarray[i];
    
    nsinteger next = i + 1;
    
    glmusiclrcmodel *nextlrcmodel = nil;
    if (next < [glmusicplayer defaultplayer].musiclrcarray.count) {
      nextlrcmodel = [glmusicplayer defaultplayer].musiclrcarray[next];
    }
    
    if (self.currentlcrindex != i && currenttime >= model.time)
    {
      bool show = no;
      if (nextlrcmodel) {
        if (currenttime < nextlrcmodel.time) {
          show = yes;
        }
      }else{
        show = yes;
      }
      
      if (show) {
        nsindexpath *currentindexpath = [nsindexpath indexpathforrow:i insection:0];
        nsindexpath *previousindexpath = [nsindexpath indexpathforrow:self.currentlcrindex insection:0];
        
        self.currentlcrindex = i;
        
        musiclrctableviewcell *currentcell = [self.lrctableview cellforrowatindexpath:currentindexpath];
        musiclrctableviewcell *previouscell = [self.lrctableview cellforrowatindexpath:previousindexpath];
        
        //设置当前行的状态
        [currentcell reloadcellforselect:yes];
        //取消上一行的选中状态
        [previouscell reloadcellforselect:no];
  
  
        if (!self.isdrag) {
          [self.lrctableview scrolltorowatindexpath:currentindexpath atscrollposition:uitableviewscrollpositionmiddle animated:yes];
        }
      }
    }
    
    if (self.currentlcrindex == i) {
      musiclrctableviewcell *cell = [self.lrctableview cellforrowatindexpath:[nsindexpath indexpathforrow:i insection:0]];
      
      cgfloat totaltime = 0;
      if (nextlrcmodel) {
        totaltime = nextlrcmodel.time - model.time;
      }else{
        totaltime = [glmusicplayer defaultplayer].duration.minute * 60 + [glmusicplayer defaultplayer].duration.second - model.time;
      }
      cgfloat progresstime = currenttime - model.time;
      cell.lrclable.progress = progresstime / totaltime;
    }
  }
}

到此为止,我们一个简单的播放器就差不多实现了,但是这...并没有完,相比qq音乐而言,它还差一个播放顺序切换的功能和锁屏播放功能

4、切换播放顺序

这个比较简单,只是需要注意在切换的时候,注意数组的越界和不同模式的处理

这里,我定义了如下几种模式

?
1
2
3
4
5
6
typedef ns_enum(nsinteger,glloopstate){
  glsingleloop = 0,//单曲循环
  glforeverloop,//重复循环
  glrandomloop,//随机播放
  glonceloop//列表一次顺序播放
};

切换代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//不同状态下 播放歌曲
- (void)playmusicforstate
{
  switch (self.loopstate) {
    case glsingleloop:
    {
      [self playmusicatindex:self.currentindex];
    }
      break;
    case glforeverloop:
    {
      if (self.currentindex == self.musiclistarray.count-1) {
        [self playmusicatindex:0];
      }else{
        [self playmusicatindex:self.currentindex + 1];
      }
    }
      break;
    case glrandomloop:
    {
      //取随机值
      int index = arc4random() % self.musiclistarray.count;
      [self playmusicatindex:index];
    }
      break;
    case glonceloop:
    {
      if (self.currentindex == self.musiclistarray.count-1) {
        [self stop];
      }else{
        [self playmusicatindex:self.currentindex + 1];
      }
    }
      break;
      
    default:
      break;
  }
}

5、锁屏播放

就如上图2中那样,由于在ios 11中好像不能支持背景图片和歌词展示,可能是为了界面更加简洁吧,所以我这里也就没有加该功功能,只是简答的有个播放界面和几个控制按钮

首先需要在工程中这样设置,保证在后台播放

iOS之基于FreeStreamer的简单音乐播放器示例

然后就是在appdelegate中添加如下代码

?
1
2
3
4
5
6
  avaudiosession *session = [avaudiosession sharedinstance];
//  [session setactive:yes error:nil];
  [session setactive:yes withoptions:avaudiosessionsetactiveoptionnotifyothersondeactivation error:nil];
  [session setcategory:avaudiosessioncategoryplayback error:nil];
  
  [[uiapplication sharedapplication] beginreceivingremotecontrolevents];

并且添加控制事件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#pragma mark == event response
-(void)remotecontrolreceivedwithevent:(uievent *)event{
  
  nslog(@"%ld",event.subtype);
  
  if (event.type == uieventtyperemotecontrol) {
    switch (event.subtype) {
      case uieventsubtyperemotecontrolplay:
      {
        //点击播放按钮或者耳机线控中间那个按钮
        [[glmusicplayer defaultplayer] pause];
      }
        break;
      case uieventsubtyperemotecontrolpause:
      {
        //点击暂停按钮
        [[glmusicplayer defaultplayer] pause];
      }
        break;
      case uieventsubtyperemotecontrolstop :
      {
        //点击停止按钮
        [[glmusicplayer defaultplayer] stop];
      }
        break;
      case uieventsubtyperemotecontroltoggleplaypause:
      {
        //点击播放与暂停开关按钮(iphone抽屉中使用这个)
        [[glmusicplayer defaultplayer] pause];
      }
        break;
      case uieventsubtyperemotecontrolnexttrack:
      {
        //点击下一曲按钮或者耳机中间按钮两下
        [[glmusicplayer defaultplayer] playnext];
      }
        break;
      case uieventsubtyperemotecontrolprevioustrack:
      {
        //点击上一曲按钮或者耳机中间按钮三下
        [[glmusicplayer defaultplayer] playfont];
      }
        break;
      case uieventsubtyperemotecontrolbeginseekingbackward:
      {
        //快退开始 点击耳机中间按钮三下不放开
      }
        break;
      case uieventsubtyperemotecontrolendseekingbackward:
      {
        //快退结束 耳机快退控制松开后
      }
        break;
      case uieventsubtyperemotecontrolbeginseekingforward:
      {
        //开始快进 耳机中间按钮两下不放开
      }
        break;
      case uieventsubtyperemotecontrolendseekingforward:
      {
        //快进结束 耳机快进操作松开后
      }
        break;
        
      default:
        break;
    }
    
  }
}

beginreceivingremotecontrolevents为允许传递远程控制事件,remotecontrolreceivedwithevent为接收一个远程控制事件,关于控制事件的类型,在代码中,已经注释过,这里就不再说了。

控制事件搞定了,剩下的就是界面的展示了,主要是歌曲信息的展示,通过如下的代码就能实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
nsmutabledictionary *musicinfodict = [[nsmutabledictionary alloc] init];
//设置歌曲题目
[musicinfodict setobject:self.currenttitle forkey:mpmediaitempropertytitle];
//设置歌手名
[musicinfodict setobject:@"" forkey:mpmediaitempropertyartist];
//设置专辑名
[musicinfodict setobject:@"" forkey:mpmediaitempropertyalbumtitle];
//设置歌曲时长
[musicinfodict setobject:[nsnumber numberwithfloat:totaltime]
         forkey:mpmediaitempropertyplaybackduration];
//设置已经播放时长
[musicinfodict setobject:[nsnumber numberwithfloat:currenttime]
         forkey:mpnowplayinginfopropertyelapsedplaybacktime];
 
[[mpnowplayinginfocenter defaultcenter] setnowplayinginfo:musicinfodict];

关于歌曲信息的设置,可以不按照我这样,定时器中时刻进行刷新,只需要在播放、暂停、快进快退这些时间有变化的地方传入当前歌曲的关键信息就可以,系统会自动去根据播放情况去更新锁屏界面上的进度条,而不需要我们时刻传入当前播放时间。这里我为了偷懒,就加在里面了。为了防止频繁操作,我采取了个方法,在其他地方看到的,就是监听锁屏情况

?
1
2
3
4
5
6
7
8
9
10
11
12
13
//监听锁屏状态 lock=1则为锁屏状态
 uint64_t locked;
 __block int token = 0;
 notify_register_dispatch("com.apple.springboard.lockstate",&token,dispatch_get_main_queue(),^(int t){
 });
 notify_get_state(token, &locked);
 
 //监听屏幕点亮状态 screenlight = 1则为变暗关闭状态
 uint64_t screenlight;
 __block int lighttoken = 0;
 notify_register_dispatch("com.apple.springboard.hasblankedscreen",&lighttoken,dispatch_get_main_queue(),^(int t){
 });
 notify_get_state(lighttoken, &screenlight);

通过该情况来设置。

在上面锁屏播放的过程中,出现一个问题,就是当我切换歌曲的时候,不管是在锁屏情况下,还是在app内

通过各种查找,大概找到问题,首先在appdelegate中将[session setactive:yes error:nil]改成了[session setactive:yes withoptions:avaudiosessionsetactiveoptionnotifyothersondeactivation error:nil],然后再播放的地方加了一个[self stop],先停止播放

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)playfromurl:(nsurl *)url
{
  //根据地址 在本地找歌词
  nsmutabledictionary *dic = [nsmutabledictionary dictionarywithcontentsoffile:[[nsbundle mainbundle] pathforresource:@"musiclist" oftype:@"plist"]];
  for (nsstring *playstringkey in dic.allkeys) {
    if ([[dic valueforkey:playstringkey] isequaltostring:url.absolutestring]) {
      self.currenttitle = playstringkey;
      break;
    }
  }
  
  [self stop];
  if (![url.absolutestring isequaltostring:self.url.absolutestring]) {
    [super playfromurl:url];
  }else{
    [self play];
  }

到此为止,一个简单的播放器就差不多了,由于时间关系,可能还有些bug,希望大家能多多提出来,我好进行修正。下面还是附上 demo ,后续我还将加一个功能,因为这两天公司有个很老的项目,有个下载问题,有点蛋疼,所以准备些一个队列下载,然后顺便加到播放器上。

说说遇到的坑

第一个就是我们项目中也有用到科大讯飞的语音.和录音的功能这些东西都需要对avaudiosession进行操作.在切换使用avaudiosession的时候就会报[avaudiosession setactive:withoptions:error:]: deactivating an audio session that has running i/o. all i/o should be stopped or paused prior to deactivating the audio session. 这样的错误,这个错会导致音频在播放但是没有声音. 我的解决办法是搜索框架中所有的setactive:no,把no改成yes,这个问题就完美的解决了.

第二个坑就是当刚开始缓存但是没有出声音的时候这个时候调暂停的方法是没用的,即使调用了暂停的方法.但是音频还是会播放.我刚开始的解决办法是在监听fsaudiostreamstate的kfsaudiostreamplaying状态.在playfromurl:的时候设置了一个属性buffering置为yes,在调用kfsaudiostreamplaying的置为no,这样在暂停方法里这样写

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (void)suspentfm {
   
  if (self.issuspendfm==yes) return;
   
  if (self.buffering ==yes) {
    [_audiostream stop];
  }else {
     
    [_audiostream pause];
     
  }
  self.issuspendfm = yes;
  _suspentbtn.hidden = no;
   
   
}

就解决了这个问题.但是解决的并不完美.kfsaudiostreamplaying这个状态会调用很多次.这样在少数情况下还是会有问题,具体情况已经忘了.于是乎我就放出了终极大招在定时器里监听进度

?
1
2
3
4
5
6
if ( progressview.progress<0.007) {
   self.buffering = yes;
 }else {
   
   self.buffering = no;
 }

到这里才完美的解决这个问题

在接下来说使用小技巧吧.就是缓存的进度和播放的进度

?
1
2
3
4
5
6
7
8
9
10
fsstreamposition cur = self.audiostream.currenttimeplayed;
  self.playbacktime =cur.playbacktimeinseconds/1;
  self.progressview.progress = cur.position;//播放进度
  self.progress = cur.position;
  float prebuffer = (float)self.audiostream.prebufferedbytecount;
  float contentlength = (float)self.audiostream.contentlength;
   
  if (contentlength>0) {
    self.progressview.cacheprogress = prebuffer /contentlength;//缓存进度
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cocoachina.com/ios/20171116/21184.html

延伸 · 阅读

精彩推荐
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28