Spotify如何自定义iOS上的媒体播放控件?
Spotify在iOS上有一个非常有趣的控制中心集成。 注意下面的汉堡button。
同样的事情是在锁屏上!
他们如何做到这一点? MPMediaCenter中是否有API?
是的,有一个API
查看苹果文档中有关远程控制事件的说明,您将得到MPRemoteCommand
和MPRemoteCommandCenter
突出显示的两个类。 查找MPRemoteCommandCenter将显示你有很多像likeCommand
或dislikeCommand
命令你可以添加处理程序。 向这些命令添加处理程序会使它们在控制中心显示出来。
下面是一些在你的屏幕截图上显示几乎完全相同的结果的一体式代码:
- (void)showCustomizedControlCenter { /* basic audio initialization */ NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.mp3", [[NSBundle mainBundle] resourcePath]]; NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; self.player.numberOfLoops = -1; [self.player play]; /* registering as global audio playback */ [[AVAudioSession sharedInstance] setActive:YES error:nil]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; /* the cool control center registration */ MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter]; [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent *event) { return MPRemoteCommandHandlerStatusSuccess; }]; [commandCenter.dislikeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent *event) { return MPRemoteCommandHandlerStatusSuccess; }]; [commandCenter.likeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent *event) { return MPRemoteCommandHandlerStatusSuccess; }]; [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent *event) { return MPRemoteCommandHandlerStatusSuccess; }]; /* setting the track title, album title and button texts to match the screenshot */ commandCenter.likeCommand.localizedTitle = @"Thumb Up"; commandCenter.dislikeCommand.localizedTitle = @"Thumb down"; MPNowPlayingInfoCenter* info = [MPNowPlayingInfoCenter defaultCenter]; NSMutableDictionary* newInfo = [NSMutableDictionary dictionary]; [newInfo setObject:@"Mixtape" forKey:MPMediaItemPropertyTitle]; [newInfo setObject:@"Jamie Cullum" forKey:MPMediaItemPropertyArtist]; info.nowPlayingInfo = newInfo; }
除了写你需要的代码
- 添加
AVFoundation
到您的项目 -
#import <AVFoundation/AVFoundation.h>
和#import <MediaPlayer/MediaPlayer.h>
- 在应用程序设置中激活背景模式
"Audio and AirPlay"
。