在设置这个锁屏之前,首先得设置应用支持后台音乐播放,TAGETS->Info->Required background modes->App plays audio or streams audio/video using AirPlay
或者在plist中设置如上边数据。
1.添加self为第一响应者,并设置接收远程控制
[self becomeFirstResponder];[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
-(BOOL)becomeFirstResponder{
return YES;
}
2.利用data初始化音乐播放器AVAudioPlayer,并设置prepareToPlay。
self.AudioPlayer = [[AVAudioPlayer alloc]initWithData:data error:&error];
[self.AudioPlayer prepareToPlay];
3.在播放/暂停的按钮控制中,设置音乐锁屏信息,一般每次播放和暂停的时候刷新锁屏信息
- (IBAction)clickbtn:(id)sender {UIButton *btn = sender;if (btn.tag == 1) {[self.AudioPlayer play];}else{[self.AudioPlayer pause];}btn.tag *= -1;if (self.AudioPlayer.isPlaying) {NSLog(@"yes");}else{NSLog(@"no");}NSMutableDictionary *songInfo = [ [NSMutableDictionary alloc] init];//锁屏图片UIImage *img = [UIImage imageNamed:@"logo152"];if (img) {MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc]initWithImage:img];[songInfo setObject: albumArt forKey:MPMediaItemPropertyArtwork ];}//锁屏标题NSString *title = @"music";[songInfo setObject:[NSNumber numberWithFloat:100] forKey:MPMediaItemPropertyPlaybackDuration];[songInfo setObject:title forKey:MPMediaItemPropertyTitle];[songInfo setObject:title forKey:MPMediaItemPropertyAlbumTitle];[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo ];}
4.添加接收远程控制的方法
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {switch (event.subtype){case UIEventSubtypeRemoteControlPlay:NSLog(@"%s-%d",__FUNCTION__,__LINE__);//play [self.AudioPlayer play];break;case UIEventSubtypeRemoteControlPause: // NSLog(@"%s-%d",__FUNCTION__,__LINE__);//pause [self.AudioPlayer pause];break;case UIEventSubtypeRemoteControlStop:NSLog(@"%s-%d",__FUNCTION__,__LINE__);//stopbreak;default:break;} }