iOS音乐后台播放及锁屏信息显示

时间:2022-11-20 09:37:37

本文实例为大家分享了ios实现音乐的后台播放,以及播放时,可以控制其暂停,下一首等操作,以及锁屏图片歌曲名等的显示

此实例需要真机调试,效果图如下:

iOS音乐后台播放及锁屏信息显示

工程下载:github工程下载

实现步骤:

1、首先修改info.plist

iOS音乐后台播放及锁屏信息显示

2、其次引入两个需要的框架

?
1
2
#import <avfoundation/avfoundation.h>
#import <mediaplayer/mediaplayer.h>

3、设置播放器及后台播放

?
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)viewdidload {
  [super viewdidload];
//  设置后台播放
  [[avaudiosession sharedinstance] setcategory:avaudiosessioncategoryplayback error:nil];
 
//  设置播放器
  nsurl *url = [nsurl fileurlwithpath:[[nsbundle mainbundle] pathforresource:@"那些花儿" oftype:@"mp3"] ];
  _player = [[avplayer alloc] initwithurl:url];
  [_player play];
  _isplayingnow = yes;
 
  //后台播放显示信息设置
  [self setplayinginfo];
}
 
#pragma mark - 接收方法的设置
- (void)remotecontrolreceivedwithevent:(uievent *)event {
  if (event.type == uieventtyperemotecontrol) { //判断是否为远程控制
    switch (event.subtype) {
      case uieventsubtyperemotecontrolplay:
        if (!_isplayingnow) {
          [_player play];
        }
        _isplayingnow = !_isplayingnow;
        break;
      case uieventsubtyperemotecontrolpause:
        if (_isplayingnow) {
          [_player pause];
        }
        _isplayingnow = !_isplayingnow;
        break;
      case uieventsubtyperemotecontrolnexttrack:
        nslog(@"下一首");
        break;
      case uieventsubtyperemotecontrolprevioustrack:
        nslog(@"上一首 ");
        break;
      default:
        break;
    }
  }
}

4、设置后台播放时显示的东西,例如歌曲名字,图片等

?
1
2
3
4
5
6
7
8
9
10
- (void)setplayinginfo {
//  <mediaplayer/mediaplayer.h>
  mpmediaitemartwork *artwork = [[mpmediaitemartwork alloc] initwithimage:[uiimage imagenamed:@"pushu.jpg"]];
 
  nsdictionary *dic = @{mpmediaitempropertytitle:@"那些花儿",
             mpmediaitempropertyartist:@"朴树",
             mpmediaitempropertyartwork:artwork
             };
  [[mpnowplayinginfocenter defaultcenter] setnowplayinginfo:dic];
}

5、远程控制设置

?
1
2
3
4
5
6
7
8
9
10
11
- (void)viewdidappear:(bool)animated {
//  接受远程控制
  [self becomefirstresponder];
  [[uiapplication sharedapplication] beginreceivingremotecontrolevents];
}
 
- (void)viewdiddisappear:(bool)animated {
//  取消远程控制
  [self resignfirstresponder];
  [[uiapplication sharedapplication] endreceivingremotecontrolevents];
}

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

原文链接:https://blog.csdn.net/Zsk_Zane/article/details/47320621