在Info.plist里面添加 Required background modes, 展开后选择App plays audio or streams audio/video using AirPlay
//设置音乐后台播放的会话类型
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error = nil;
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
if (error) {
NSLog(@"%s %@", __func__, error);
}
[session setActive:YES error:nil];
//开启远程事件(锁屏时使用)
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
#pragma mark 接收远程事件
-(void)remoteControlReceivedWithEvent:(UIEvent *)event{
//判断是否为远程事件
if (event.type == UIEventTypeRemoteControl) {
//调用
[self myRemoteEventBlock:event];
}
}
- (void)myRemoteEventBlock:(UIEvent*)event{
switch (event.subtype) {
case UIEventSubtypeRemoteControlPlay:
[self.avAudioPlayer play];
break;
case UIEventSubtypeRemoteControlPause:
[self.avAudioPlayer pause];
break;
case UIEventSubtypeRemoteControlPreviousTrack:
[self last];
break;
case UIEventSubtypeRemoteControlNextTrack:
[self next];
break;
default:
break;
}
};
-(void)next{
if (self.flag < self.array.count - 1) {
self.flag++;
}else{
self.flag = 0;
}
[self setupUI:self.flag];
}
-(void)last{
if (self.flag <= 0) {
self.flag = self.array.count - 1;
}else{
self.flag --;
}
[self setupUI:self.flag];
}
//锁屏界面
NSMutableDictionary *info = [NSMutableDictionary dictionary];
//设置专辑名称
info[MPMediaItemPropertyAlbumTitle] = @"网络热曲";
//设置歌曲名
info[MPMediaItemPropertyTitle] = self.array[index];
//设置歌手
info[MPMediaItemPropertyArtist] = self.array[index];
//设置专辑图片, 这里图片加载不出来的时候, 会崩溃
UIImage *image = [UIImage imageNamed:@"01"];
MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
info[MPMediaItemPropertyArtwork] = artwork;
//设置歌曲时间
info[MPMediaItemPropertyPlaybackDuration] = @(self.avAudioPlayer.duration);
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;