實現鎖屏也能控制播放,需要兩件事:申請後台音頻權限,以及響應系統的遠程控制事件;鎖屏上的歌名、歌手、封面則由 MPNowPlayingInfoCenter 負責。下面直接上關鍵代碼。
在 AppDelegate 中配置 AVAudioSession,把 category 設為 Playback 並激活:
- (void)setAudioBackstagePlay{ AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil]; [audioSession setActive:YES error:nil]; }
重寫 remoteControlReceivedWithEvent:,根據 subtype 分發到播放、暫停、上一首、下一首等具體邏輯:
//重寫父類方法,接受外部事件的處理 - (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent { NSLog(@"remote"); if (receivedEvent.type == UIEventTypeRemoteControl) { switch (receivedEvent.subtype) { // 得到事件類型 case UIEventSubtypeRemoteControlTogglePlayPause: // 暫停 ios6 [_player musicPause]; // 調用你所在項目的暫停按鈕的響應方法 下面的也是如此 break; case UIEventSubtypeRemoteControlPreviousTrack: // 上一首 [self lastMusic]; break; case UIEventSubtypeRemoteControlNextTrack: // 下一首 [self nextMusic]; break; case UIEventSubtypeRemoteControlPlay: //播放 [_player musicPlay]; break; case UIEventSubtypeRemoteControlPause: // 暫停 ios7 [_player musicPause]; break; default: break; } } }
通過 MPNowPlayingInfoCenter 寫入標題、歌手、時長、進度、播放速率與封面。封面如果是網絡圖,需要先異步下載再回填:
- (void)configNowPlayingCenter { NSLog(@"鎖屏設置"); YBVideoListModel * list = _model.audioList[_currentIndexPath.row]; //以下代碼是加載鎖屏顯示網絡圖片以及其他設置 [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:list.thumbUrl] options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (image == nil) { image = [UIImage imageNamed:@"default_music"]; } NSMutableDictionary * info = [NSMutableDictionary dictionary]; //音樂的標題 [info setObject:list.title forKey:MPMediaItemPropertyTitle]; //音樂的藝術家 NSString *author= list.singer; [info setObject:author forKey:MPMediaItemPropertyArtist]; //音樂的播放時間 [info setObject:@(_player.player.currentTime.value) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; //音樂的播放速度 [info setObject:@(1) forKey:MPNowPlayingInfoPropertyPlaybackRate]; //音樂的總時間 [info setObject:@(list.duration) forKey:MPMediaItemPropertyPlaybackDuration]; //音樂的封面 MPMediaItemArtwork * artwork = [[MPMediaItemArtwork alloc] initWithImage:image]; [info setObject:artwork forKey:MPMediaItemPropertyArtwork]; //完成設置 [[MPNowPlayingInfoCenter defaultCenter]setNowPlayingInfo:info]; }]; }
補充兩個實踐要點:播放進度需要在播放過程中定期更新 elapsedPlaybackTime,鎖屏上的進度條才會走動;切歌時要同步刷新 NowPlayingInfo,否則鎖屏顯示的還是上一首的信息。
以上就是 iOS 鎖屏控制音樂與鎖屏信息設置的完整示例代碼。