第一步:在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]; }