公司的app里面有后台音频播放功能,最近发现,当在锁屏界面(后台)时,不能控制播放页面的音频播放,是因为没有实现远程控制事件处理。

下面说说大概实现过程:由于后台播放功能早已实现(不做详细叙述),这里主要记录一下远程控制的实现(方便以后复习)。

1、在文件APPDelegate.m里,实现方法“- (void)remoteControlReceivedWithEvent:(UIEvent *)event”的重写,用来接收控制中心的事件。

//  在APPDelegate.m中声明一个通知事件的key
NSString *const AppDelegateReceiveRemoteEventsNotification = @"AppDelegateReceiveRemoteEventsNotification";/// 锁屏页面的控制事件(必须在这里重写该方法,在播放页面重写不起作用)- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{if (event.type == UIEventTypeRemoteControl) {// 发送通知给音频播放界面 进行某些处理[[NSNotificationCenter defaultCenter] postNotificationName:AppDelegateReceiveRemoteEventsNotification object:event];}
}

Appdelegate里就设置这些。

2、在音频播放界面

// 设置控制中心交互需要导入
#import <MediaPlayer/MediaPlayer.h>
/// 注册通知
- (void) registerAllNotifications
{// 后台通知[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(apllicationWillResignActiveNotification:) name:UIApplicationWillResignActiveNotification object:nil];// 进入前台通知[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(apllicationWillEnterForegroundNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];// 锁屏界面事件[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AppDelegateReceiveRemoteEventsNotification:) name:AppDelegateReceiveRemoteEventsNotification object:nil];}
#pragma mark - 通知方法实现/// 进入后台
- (void) apllicationWillResignActiveNotification:(NSNotification *)n
{NSError *error = nil;// 后台播放代码AVAudioSession *session = [AVAudioSession sharedInstance];[session setActive:YES error:&error];if(error) {NSLog(@"ListenPlayView background error0: %@", error.description);}[session setCategory:AVAudioSessionCategoryPlayback error:&error];if(error) {NSLog(@"ListenPlayView background error1: %@", error.description);}/// 进后台 设置接收远程控制[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];// 上面代码实现后台播放 几分钟后会停止播放// 添加任务id 实现后台连续播放backTaskID = [self backgroundPlayerID:backTaskID];
}// 实现一下backgroundPlayerID:这个方法:
- (UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{NSError *error = nil;// 设置并激活音频会话类别AVAudioSession *session = [AVAudioSession sharedInstance];[session setCategory:AVAudioSessionCategoryPlayback error:nil];if(error) {NSLog(@"ListenPlayView background error2: %@", error.description);}[session setActive:YES error:nil];if(error) {NSLog(@"ListenPlayView background error3: %@", error.description);}// 设置后台任务IDUIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];if(newTaskId != UIBackgroundTaskInvalid && backTaskId != UIBackgroundTaskInvalid) {[[UIApplication sharedApplication] endBackgroundTask:backTaskId];}return newTaskId;
}/// 进入前台通知
- (void) apllicationWillEnterForegroundNotification:(NSNotification *)n {// 进前台 设置不接受远程控制[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
}/// 远程控制事件通知
- (void)AppDelegateReceiveRemoteEventsNotification:(NSNotification*)noti
{if (!noti) return;if (!noti.object) return;if (![noti.object isKindOfClass:[UIEvent class]]) return;UIEvent *event = (UIEvent *)noti.object;if (event.type == UIEventTypeRemoteControl) {// 根据远程控制事件类型,在播放界面设置播放、暂停、下一个、上一个switch (event.subtype) {case UIEventSubtypeRemoteControlPlay:// playbreak;case UIEventSubtypeRemoteControlPause:// pausebreak;case UIEventSubtypeRemoteControlNextTrack:// nextbreak;case UIEventSubtypeRemoteControlPreviousTrack:// lastbreak;default: break;}}
}
/// 移除所有通知
- (void)removeAllNotifications {[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];[[NSNotificationCenter defaultCenter] removeObserver:self name:AppDelegateReceiveRemoteEventsNotification object:nil];[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];}

上面这些实现了控制中心和播放界面的交互。此时,控制中心还没有显示当前播放的音频信息(嗯,我还没有设置)。如下:

/// 设置锁屏界面的播放音频的相关信息
/// 可在适当时机调用该方法(开始播放时、将要进入后台、音频切换)
- (void) setupNowPlayingAudioInfo
{/** 设置信息的类型*  MPMediaItemPropertyAlbumTitle : 专辑名*  MPMediaItemPropertyAlbumTrackCount : 专辑个数*  MPMediaItemPropertyAlbumTrackNumber : 当前播放的专辑位置*  MPMediaItemPropertyArtist : 艺术家*  MPMediaItemPropertyArtwork : 封面*  MPMediaItemPropertyComposer : 作曲家*  MPMediaItemPropertyDiscCount  : 迪斯科 数量*  MPMediaItemPropertyDiscNumber : 当前位置*  MPMediaItemPropertyGenre : 流派*  MPMediaItemPropertyPersistentID : ID*  MPMediaItemPropertyPlaybackDuration : 后台播放时长*  MPMediaItemPropertyTitle : 标题*/NSMutableDictionary *songDict = [NSMutableDictionary dictionary];// 音频名字[songDict setObject:@"她来听我的演唱会"  forKey:MPMediaItemPropertyTitle];// 歌手[songDict setObject:@"张学友"  forKey:MPMediaItemPropertyArtist];// 歌曲的总时间[songDict setObject:@(200) forKeyedSubscript:MPMediaItemPropertyPlaybackDuration];// 当前时间[songDict setObject:@(30) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];// 播放速率[songDict setObject:@(1.0) forKey:MPNowPlayingInfoPropertyPlaybackRate];// 锁屏音频封面MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"封面.png"]];[songDict setObject:artwork forKey:MPMediaItemPropertyArtwork];// 设置控制中心歌曲信息[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songDict];
}

这时,锁屏界面已经可以显示音频对应的信息了。

还有最后一步设置(动态设置控制中心的按钮状态),如:当前播放的音频是播放列表最后一条,设置控制中心的下一个按钮不可点击。。。

/// 设置控制中心的按钮状态(保持与播放界面对应按钮状态一致)
/// 调用时机(如切换音频时,设置锁屏界面音频信息时)
- (void) setupRemoteControlButtonStatus
{// 只有设置了target 才能设置控制中心(锁屏界面)的按钮状态// 设置控制中心下一个按钮 和播放页面的下一个按钮状态同步MPRemoteCommand *next = [MPRemoteCommandCenter sharedCommandCenter].nextTrackCommand;next.enabled = self.nextButton.enabled;[next addTarget:self action:@selector(remoteCommandAction:)];// 设置控制中心上一个按钮 和播放页面的上一个按钮状态同步MPRemoteCommand *last = [MPRemoteCommandCenter sharedCommandCenter].previousTrackCommand;last.enabled = self.theLastButton.enabled;[last addTarget:self action:@selector(remoteCommandAction:)];// 设置控制中心播放|暂停按钮 和 播放页面的播放|暂停按钮状态同步MPRemoteCommand *play = [MPRemoteCommandCenter sharedCommandCenter].playCommand;play.enabled = self.playButton.enabled;[play addTarget:self action:@selector(remoteCommandAction:)];MPRemoteCommand *pause = [MPRemoteCommandCenter sharedCommandCenter].pauseCommand;pause.enabled = self.playButton.enabled;[pause addTarget:self action:@selector(remoteCommandAction:)];
}/// 实现target action
- (void)remoteCommandAction:(MPRemoteCommand *)com
{// 这里不用具体做些什么 do nothing..// 控制中心的事件已经在通知AppDelegateReceiveRemoteEventsNotification里实现了
}

设置完毕(这些设置已经足够公司app的需要了,有需要再补充)。

参考了一下其他博客,如https://www.cnblogs.com/gchlcc/p/5582571.html

转载于:https://my.oschina.net/mustard22/blog/1632107

iOS锁屏界面音频播放控制相关推荐

  1. iOS音乐后台播放、锁屏封面及播放控制

    在默认情况下App被切换到后台时,音乐的就停止播放了,但音乐类App的一般都会需要在后台继续播放,这样用户就可以一边听音乐,一边操作其他的App.对于这种情况我们可以对App做一些简单的配置,实现后台 ...

  2. iOS - 音频后台播放设置及锁屏界面的显示与控制

    音频后台播放设置 1.先在项目 的Capabilities中进行设置,开启后台模式 2.激活音频会话 其它地方也可以,只要保证能执行到以下代码块的内容即可,这里我选择在AppDelegate.m里设置 ...

  3. iOS锁屏页面控制音乐播放

    //1.调整音频会话设置,确保应用进入后台或静音开关已开启时音频仍将继续播放 2.锁屏状态下显示媒体信息 3.锁屏上的空间可以控制音频播放#import "ViewController.h& ...

  4. android 锁屏显示音乐播放器,Android锁屏界面控制音乐播放

    目前,在锁屏界面控制音乐播放有两种常用方式. 第一种方式:原生Android系统及自带音乐播放器. 锁屏界面端: 原生Android中,锁屏界面相关的UI由KeyguardHostView提供,Key ...

  5. GNOME 3.36正式发布,家长控制、勿扰模式、更加优雅的锁屏界面

    2020年3月11日,GNOME 3.36正式发布,被命名为 "Gresik", 是 GNOME 3 当前的最新版本.它包含了主要的新功能,以及许多小的改进和错误修复.总的来说,这 ...

  6. linux系统lockscreen,iOS 5.1.1 锁屏界面(LockScreen)仿 HTC Sense 天气插件

    以前转了一个 iOS 利用 HTC Weather Animated PerpageHTML 实现仿 HTC 天气时钟的帖子: 这天气更新了 iOS 5.1.1 的完美越狱,现在发现以前放在 Page ...

  7. iOS开发实用技术之音频播放(QQ音乐)

    音频播放 --- 一. 录音 0. 应用场景 大多数应用在即时通讯APP中, 语音发送 1. 录音步骤 导入AVFoundation框架 #import <AVFoundation/AVFoun ...

  8. 网易云音乐锁屏界面实现

    2019独角兽企业重金招聘Python工程师标准>>> ######最终效果: #完整的实现思路: App如果需要在锁屏界面上显示相关的信息和按钮, 必须先开启远程控制事件(Remo ...

  9. android 系统 锁屏界面,在安卓手机系统使用Ubuntu漂亮的锁屏界面攻略

    如果你了解Ubuntu系统,那么绝对会被它那漂亮的锁屏界面所吸引.今天我们就让广大Android用户能够提前感受一下Ubuntu系统的锁屏界面,并且不会有任何功能上的影响,所有的通知与信息都可以正常显 ...

最新文章

  1. JRebel for Android 编译神器
  2. pytorch手动实现梯度下降法,随机梯度法--基于logistic Regression并探索Mini batch作用
  3. PyTorch——深度神经网络的写作笔记
  4. 在函数‘_start’中:对‘main’未定义的引用
  5. kindeditor在线HTML编辑器
  6. fpga驱动步进电机转动指定角度_通过PLC实现步进电机定位控制的方法
  7. bat批处理脚本执行过程中,Windows运行窗口中出现中文乱码
  8. 【教程】手把手教你做外卖红包推广返利公众号搭建
  9. 前端代码是怎样智能生成的
  10. ENE轨道线的选股公式
  11. JavaScript实现人民币大小写转换
  12. 什么是网站的源代码?
  13. python 白噪声检验-Python中的白噪声时间训练
  14. 蚁群算法Ant Colony Optimization-ACO
  15. 求1+2!+3!+...20!的两种方法
  16. 基于Java的XML编辑器:Oxygen XML Editor Mac中文版
  17. 随机抽人名小程序_分析并实现一个简单的抽人程序
  18. Oralce数据库的详解解析(包括操作步骤)【1】
  19. 争对让望对思野葛对山栀注解_笠翁对韵·上卷·四支在线阅读-翻译及赏析
  20. Java——关于Excle表格的操作

热门文章

  1. 在R语言中进行局部多项式回归拟合(LOESS)
  2. 阿里巴巴开源技术体系
  3. 前端一键切换深色模式
  4. 蓝桥杯-打印菱形/字符串截断
  5. 他看了几千份技术简历,愿意把技术简历的秘籍传授给你
  6. python爬虫入门教程04:招聘信息爬取
  7. 【C语言】剖析函数递归(3)
  8. 渗透笔记之web漏洞概述
  9. Minecraft 1.18.2 forge开发 | (1) 开发环境搭建
  10. EspTouch概述