Spotify如何在iOS上自定义媒体播放控件?

Mos*_*she 13 ios mpmediaplayercontroller control-center

iOS上的Spotify有一个非常有趣的控制中心集成.注意下面的汉堡包按钮.

汉堡包

锁屏上同样的事情!

锁屏

他们是如何做到的?MPMediaCenter中有API吗?

luk*_*302 18

是的,有一个API

查看有关远程控制事件的Apple文档中的说明,您将获得两个课程MPRemoteCommandMPRemoteCommandCenter突出显示.查找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;
}
Run Code Online (Sandbox Code Playgroud)

除了编写您需要的代码

  • 添加AVFoundation到您的项目
  • #import <AVFoundation/AVFoundation.h>#import <MediaPlayer/MediaPlayer.h>
  • "Audio and AirPlay"在应用程序设置中激活背景模式.

在此输入图像描述 在此输入图像描述