iOS_后台播放控制、锁屏封面

设置后台播放

设置App的plist,使app可以在后台播放音乐。
myApp-Info.plist中添加UIBackgroundModes键值,添加子键值为audio。
合适的位置添加代码

1
2
3
AVAudioSession  *session  =  [AVAudioSession  sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];

添加播放控制器(Remote Control Events)

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
//1. 告诉系统,我们要接受远程控制事件
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//....
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}

//2. 可以成为第一响应者
- (BOOL)canBecomeFirstResponder {
return YES;
}

//3. 响应远程音乐播放控制消息
- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
switch (event.subtype) {
case UIEventSubtypeRemoteControlPlay:
nslog(@"play");
break;
case UIEventSubtypeRemoteControlPause:
nslog(@"pause");
break;
case UIEventSubtypeRemoteControlNextTrack:
nslog(@"next");
break;
case UIEventSubtypeRemoteControlPreviousTrack:
nslog(@"previous");;
break;
default:
break;
}
}
// available in iPhone OS 3.0
UIEventSubtypeNone = 0,

// for UIEventTypeMotion, available in iPhone OS 3.0
UIEventSubtypeMotionShake = 1,

//这之后的是我们需要关注的枚举信息
// for UIEventTypeRemoteControl, available in iOS 4.0
//点击播放按钮或者耳机线控中间那个按钮
UIEventSubtypeRemoteControlPlay = 100,

//点击暂停按钮
UIEventSubtypeRemoteControlPause = 101,

//点击停止按钮
UIEventSubtypeRemoteControlStop = 102,

//点击播放与暂停开关按钮(iphone抽屉中使用这个)
UIEventSubtypeRemoteControlTogglePlayPause = 103,

//点击下一曲按钮或者耳机中间按钮两下
UIEventSubtypeRemoteControlNextTrack = 104,

//点击上一曲按钮或者耳机中间按钮三下
UIEventSubtypeRemoteControlPreviousTrack = 105,

//快退开始 点击耳机中间按钮三下不放开
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,

//快退结束 耳机快退控制松开后
UIEventSubtypeRemoteControlEndSeekingBackward = 107,

//开始快进 耳机中间按钮两下不放开
UIEventSubtypeRemoteControlBeginSeekingForward = 108,

//快进结束 耳机快进操作松开后
UIEventSubtypeRemoteControlEndSeekingForward = 109,

设置后台信息显示及锁屏界面设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 #import <MediaPlayer/MediaPlayer.h>
- (void)setLockingInfo {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
//设置歌曲题目
[dict setObject:@"题目" forKey:MPMediaItemPropertyTitle];
//设置歌手名
[dict setObject:@"歌手" forKey:MPMediaItemPropertyArtist];
//设置专辑名
[dict setObject:@"专辑" forKey:MPMediaItemPropertyAlbumTitle];
//设置显示的图片
UIImage *newImage = [UIImage imageNamed:@"43.png"];
[dict setObject:[[MPMediaItemArtwork alloc] initWithImage:newImage] forKey:MPMediaItemPropertyArtwork];
//设置歌曲时长
[dict setObject:[NSNumber numberWithDouble:300] forKey:MPMediaItemPropertyPlaybackDuration];
//设置已经播放时长
[dict setObject:[NSNumber numberWithDouble:150] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
//更新字典
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
}