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

该文章展示了如何在iOS应用中设置远程命令中心(MPRemoteCommandCenter)来实现播放/暂停、上一曲、下一曲以及拖动进度条的功能。在实例化对象时初始化这些控制,确保不会因多次调用引起问题。代码详细定义了各种命令的处理回调。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

避免多次调用会出现问题,可以在页面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博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值