我正在使用 Apple 的新 Apple Music API 来制作应用程序。我有一个带有歌曲列表的屏幕,用户可以点击其中一个来播放它。我的代码部分有效。点按的歌曲会播放,但不会显示在控制中心。控制中心空无一人,好像什么都没有播放。
- (void)viewDidLoad {
[super viewDidLoad];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
[[[MPRemoteCommandCenter sharedCommandCenter] playCommand] addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
NSLog(@"play");
return MPRemoteCommandHandlerStatusSuccess;
}];
[[[MPRemoteCommandCenter sharedCommandCenter] pauseCommand] addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
NSLog(@"pause");
return MPRemoteCommandHandlerStatusSuccess;
}];
[[[MPRemoteCommandCenter sharedCommandCenter] stopCommand] addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
return MPRemoteCommandHandlerStatusSuccess;
}];
[[[MPRemoteCommandCenter sharedCommandCenter] togglePlayPauseCommand] addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
return MPRemoteCommandHandlerStatusSuccess;
}];
[[MPRemoteCommandCenter sharedCommandCenter] playCommand].enabled = YES;
[[MPRemoteCommandCenter sharedCommandCenter] pauseCommand].enabled = YES;
[[MPRemoteCommandCenter sharedCommandCenter] stopCommand].enabled = YES;
[[MPRemoteCommandCenter sharedCommandCenter] togglePlayPauseCommand].enabled = YES;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];
}
```
点击单元格时:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MPMusicPlayerApplicationController *controller = [MPMusicPlayerController applicationQueuePlayer];
[controller performQueueTransaction:^(MPMusicPlayerControllerMutableQueue * _Nonnull queue) {
MPMusicPlayerStoreQueueDescriptor *queueDescripter = [[MPMusicPlayerStoreQueueDescriptor alloc] initWithStoreIDs:@[_album.songs[indexPath.row].identifier]];
[queue insertQueueDescriptor:queueDescripter afterItem:nil];
} completionHandler:^(MPMusicPlayerControllerQueue * _Nonnull queue, NSError * _Nullable error) {
[controller setNowPlayingItem:queue.items[0]];
[controller prepareToPlay];
[controller play];
MPMediaItem *item = [controller nowPlayingItem];
NSDictionary *info = @{MPMediaItemPropertyAlbumTitle:item.albumTitle, MPMediaItemPropertyArtist:album.artistName, MPMediaItemPropertyTitle:item.title, MPMediaItemPropertyArtwork:item.artwork, MPMediaItemPropertyPlaybackDuration:@(item.playbackDuration), MPNowPlayingInfoPropertyElapsedPlaybackTime:@0};
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:info];
}];
}
此外,此消息会记录到控制台。我不确定这是否与这个问题有关。
[RemoteControl] Error setting active player: (null)