IOS APP内后台音乐播放

写在开头

最近做了IOS音频、音乐后台播放相关的需求,这里主要总结一下支持后台播放以及远程控制的一些用法,在这个过程中也遇到了一些问题,会在另一个博客里面进行总结。

一、后台权限申请

1、在Info.plist文件中里设置选项Required background modes ,然后添加item0:App plays audio or streams audio/video using AirPlay 

2、设置Capabilities -> Background Modes -> 勾选 Audio,AirPlay,and Picture in Picture

 

3、在AppDelegate.m中添加代码

- (void)applicationWillResignActive:(UIApplication *)application {
    // *让app接受远程事件控制,及锁屏是控制版会出现播放按钮
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    // *后台播放代码
    AVAudioSession*session=[AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
}

二、添加控制代码

我们在这里使用MPRemoteCommandCenter添加远程控制代码,使用MPNowPlayingInfoCenter更新通知中心控制台的媒体信息。

关于这个两个控件的使用,可以在网上查询一些教程,我这里做简单的介绍,并添加一下使用过程中需要的注意事项

1、MPRemoteCommandCenter

(1)是一个响应系统外部附件(耳机)以及系统控件发出的运程控制事件对象。

(2)在使用的过程中,不可以多次调用(最好只调用一次,主要是addTarget不能多次调用),因为调用多次以后,会多次响应远程事件

- (void)setupLockScreenControlInfo {
    
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    
    // 锁屏播放    
    MPRemoteCommand *playCommand = commandCenter.playCommand;
    playCommand.enabled = YES;
    [playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"锁屏暂停后点击播放");
        if (!self.isPlaying) {
            [self playMusic];
        }
        return MPRemoteCommandHandlerStatusSuccess;
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值