想在鎖定畫面上顯示歌曲資訊、並讓實體耳機線控與鎖屏控制項生效,需要三件事:取得後台播放權限、攔截遠端控制事件、設定 Now Playing Center 的內容。以下依序說明。
在 AppDelegate 中把音訊工作階段設為播放模式並啟動:
- (void)setAudioBackstagePlay {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];
}
別忘了在 Info.plist 的 UIBackgroundModes 中加入 audio,否則切到背景就會被暫停。
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause: // iOS 6 的切換
[_player musicPause];
break;
case UIEventSubtypeRemoteControlPreviousTrack:
[self lastMusic];
break;
case UIEventSubtypeRemoteControlNextTrack:
[self nextMusic];
break;
case UIEventSubtypeRemoteControlPlay:
[_player musicPlay];
break;
case UIEventSubtypeRemoteControlPause: // iOS 7 之後獨立出來
[_player musicPause];
break;
default:
break;
}
}
}
把標題、演出者、長度、進度、封面圖組進字典,再交給 MPNowPlayingInfoCenter:
- (void)configNowPlayingCenter {
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];
[info setObject:list.singer 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,頻率約每秒一次即可,太高會白白耗電。
封面圖走網路下載時,圖片回來之前鎖屏只會顯示預設佔位圖;若希望第一眼就正確,建議先送一次文字資訊,封面回來後再補送第二次。