APP内后台播放音乐,拖动进度条

避免多次调用会出现问题,可以在页面appear的时候填入方法,以下仅是示例

调用:

- (instancetype)init {
    if ([super init]) {
        [self addUI];
        [self setupLockScreenControlInfo];
    }
    return self;
}

 方法:

- (void)setupLockScreenControlInfo {
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    // 播放和暂停按钮(耳机控制)
    MPRemoteCommand *playPauseCommand = commandCenter.togglePlayPauseCommand;
    playPauseCommand.enabled = YES;
    [playPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        if (self.isPlaying) {
            [self pause];
        }else {
            [self play];
        }
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 上一曲
    MPRemoteCommand *previousCommand = commandCenter.previousTrackCommand;
    [previousCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self previous];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 下一曲
    MPRemoteCommand *nextCommand = commandCenter.nextTrackCommand;
    nextCommand.enabled = YES;
    [nextCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        if (self.isPlaying) {
            [self stop];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self next];
        });
        
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 拖动进度条
    if (@available(iOS 9.1, *)) {
        MPRemoteCommand *changePlaybackPositionCommand = commandCenter.changePlaybackPositionCommand;
        changePlaybackPositionCommand.enabled = YES;
        [changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
            MPChangePlaybackPositionCommandEvent *positionEvent = (MPChangePlaybackPositionCommandEvent *)event;
            NSTimeInterval positionTime = positionEvent.positionTime;
            [self.player seekTo:CMTimeMake(positionTime, 1)];
            if (!self.isPlaying) {
                [self play];
            }
            return MPRemoteCommandHandlerStatusSuccess;
        }];
    }
}

参考:IOS APP内后台音乐播放_ios 后台播放音乐_阿飞小伙子_blogs的博客-CSDN博客

你可能感兴趣的:(ios,学习,objective-c,xcode)