标签:
第一步:在appDelegate中通知app支持后台播放:在方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {}
中添加如下代码:
AVAudioSession *audioSession = [AVAudioSession sharedInstance]; //默认情况下扬声器播放 [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil]; [audioSession setActive:YES error:nil];
第二步:在info.plist文件中添加一个key项
第三步:在播放控制界面接受远程控制
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:YES]; // 开始接受远程控制 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [self resignFirstResponder]; } - (void)viewWillDisappear:(BOOL)animated { // 接触远程控制 [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; [self becomeFirstResponder]; } // 重写父类成为响应者方法 - (BOOL)canBecomeFirstResponder { return YES; }
第四步:对远程控制事件作出相应的操作
//重写父类方法,接受外部事件的处理 - (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent { NSLog(@"remote"); if (receivedEvent.type == UIEventTypeRemoteControl) { switch (receivedEvent.subtype) { // 得到事件类型 case UIEventSubtypeRemoteControlTogglePlayPause: // 暂停 ios6 [self.player pause]; // 调用你所在项目的暂停按钮的响应方法 下面的也是如此 break; case UIEventSubtypeRemoteControlPreviousTrack: // 上一首 [self lastMusic:nil]; break; case UIEventSubtypeRemoteControlNextTrack: // 下一首 [self nextMusic:nil]; break; case UIEventSubtypeRemoteControlPlay: //播放 [self playMusic:nil]; break; case UIEventSubtypeRemoteControlPause: // 暂停 ios7 [self playMusic:nil]; break; default: break; } } }
第五步:设置锁屏主题
注意这个播放仅需要在播放状态改变的时候调用,例如初始化播放器,上一首下一首等操作
//Now Playing Center可以在锁屏界面展示音乐的信息,也达到增强用户体验的作用。 ////传递信息到锁屏状态下 此方法在播放歌曲与切换歌曲时调用即可 - (void)configNowPlayingCenter { NSLog(@"锁屏设置"); // BASE_INFO_FUN(@"配置NowPlayingCenter"); NSMutableDictionary * info = [NSMutableDictionary dictionary]; //音乐的标题 [info setObject:self.nameLabel.text forKey:MPMediaItemPropertyTitle]; //音乐的艺术家 NSString *author= [[self.playlistArr[self.currentNum] valueForKey:@"songinfo"] valueForKey:@"author"]; [info setObject:author forKey:MPMediaItemPropertyArtist]; //音乐的播放时间 [info setObject:@(self.player.currentTime.value) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; //音乐的播放速度 [info setObject:@(1) forKey:MPNowPlayingInfoPropertyPlaybackRate]; //音乐的总时间 [info setObject:@(self.totalTime) forKey:MPMediaItemPropertyPlaybackDuration]; //音乐的封面 MPMediaItemArtwork * artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"0.jpg"]]; [info setObject:artwork forKey:MPMediaItemPropertyArtwork]; //完成设置 [[MPNowPlayingInfoCenter defaultCenter]setNowPlayingInfo:info]; }
标签:
原文地址:http://www.cnblogs.com/sunjianfei/p/5903647.html