iOS后台播放

时间:2021-07-12 18:18:51
### 音乐后台播放
* .当程序进入后台的时候,开启后台任务 ```
- (void)applicationDidEnterBackground:(UIApplication *) {
// 开启后台任务
[application beginBackgroundTaskWithExpirationHandler:nil];
}
```
* .在项目的Targets页面,设置Capabilities,BackgroundModes选择第一项,`Audio, AirPlay and Picture in Picture` * .设置AudioSession会话 ```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 1.拿到AVAudioSession会话
AVAudioSession *session = [AVAudioSession sharedInstance];
// 2.设置类型
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
// 3.激活
[session setActive:YES error:nil]; return YES;
}
``` ### 显示锁屏信息
* .当开始播放的时候,开启锁屏信息,抽取一个方法 ```
[self updateLockInfo];
```
* .导入`MediaPlayer/MediaPlayer.h`框架,在播放信息中心设置信息 ```
- (void)updateLockInfo {
// 获取播放信息中心
MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
// 创建信息字典
NSMutableDictionary *infos = [NSMutableDictionary dictionary];
// 设置信息内容
infos[MPMediaItemPropertyAlbumTitle] = self.playingMusic.name;
infos[MPMediaItemPropertyAlbumArtist] = self.playingMusic.singer;
infos[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:self.playingMusic.icon]];
infos[MPMediaItemPropertyPlaybackDuration] = @(self.player.duration);
infos[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(self.player.currentTime);
// 根据字典设置播放中心
[center setNowPlayingInfo:infos]; // 开启远程事件
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// 让当前控制器成为第一响应者
[self becomeFirstResponder];
}
```
* .控制器默认不能成为第一响应者,需要实现以下方法 ```
- (BOOL)canBecomeFirstResponder {
return YES;
}
```
* .监听远程事件 ```
- (void)remoteControlReceiveWithEvent:(UIEvent *)event {
switch (event.subtype) {
// 当点击播放或者暂停按钮的时候
case UIEventSubtypeRemoteControlPlay:
case UIEventSubtypeRemoteControlPause:
[self playOrPauseButtonClick];
break;
// 当点击下一首按钮的时候
case UIEventSubtypeRemoteControlNextTrack:
[self nextButtonClick];
break;
// 当点击上一首按钮的时候
case UIEventSubtypeRemoteControlPreviousTrack:
[self previousButtonClick];
break;
default:
break;
}
```