在没有网络的情况下,音频的后台播放比较简单,google一下可以搜到很多资料,但是如果每次歌曲的请求都是通过网络,就不成了,有时可以也扛不了几首,这里总结下实现方法,可以实现像电台一样的功能,后台播放,网络请求歌曲,Remote控制,锁屏有封面,电话和听歌打断处理等。

初始化AudioSession和基本配置

音频播放器采用的AVPlayer ,自己进行了功能封装,暂且不谈,在程序启动的时候需要配置AudioSession,AudioSession负责应用音频的设置,比如支不支持后台,打断等等,这一步很重要,比如在viewdidload里初始化AVplayer以后要调用下面的函数:

-(void)setAudioSession{

//AudioSessionInitialize用于控制打断 ,后面会说

AudioSessionInitialize (

NULL,                          // ‘NULL’ to use the default (main) run loop

NULL,                          // ‘NULL’ to use the default run loop mode

ASAudioSessionInterruptionListener,  // a reference to your interruption callback

NULL                       // data to pass to your interruption listener callback

);

//这种方式后台,可以连续播放非网络请求歌曲,遇到网络请求歌曲就废,需要后台申请task

AVAudioSession *session = [AVAudioSession sharedInstance];

NSError *setCategoryError = nil;

BOOL success = [session setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];

if (!success)

{

/* handle the error condition */

return;

}

NSError *activationError = nil;

success = [session setActive:YES error:&activationError];

if (!success)

{

/* handle the error condition */

return;

}

}

AudioSessionInitialize用于处理中断处理,AVAudioSession主要调用setCategory和setActive方法来进行设置,AVAudioSessionCategoryPlayback一般用于支持后台播放,在官方文档可以看到其他的类型,每个分别适用于不同的场合:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

NSString *const <a href="file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/com.apple.adc.documentation.AppleiOS6.0.iOSLibrary.docset/Contents/Resources/Documents/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html#//apple_ref/doc/c_ref/AVAudioSessionCategoryAmbient"]] >
<blockquote]] > AVAudioSessionCategoryAmbient</blockquote]] >
</a]] > ;
NSString *const <a href="file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/com.apple.adc.documentation.AppleiOS6.0.iOSLibrary.docset/Contents/Resources/Documents/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html#//apple_ref/doc/c_ref/AVAudioSessionCategorySoloAmbient"]] >
<blockquote]] > AVAudioSessionCategorySoloAmbient</blockquote]] >
</a]] > ;
NSString *const <a href="file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/com.apple.adc.documentation.AppleiOS6.0.iOSLibrary.docset/Contents/Resources/Documents/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html#//apple_ref/doc/c_ref/AVAudioSessionCategoryPlayback"]] >
<blockquote]] > AVAudioSessionCategoryPlayback</blockquote]] >
</a]] > ;
NSString *const <a href="file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/com.apple.adc.documentation.AppleiOS6.0.iOSLibrary.docset/Contents/Resources/Documents/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html#//apple_ref/doc/c_ref/AVAudioSessionCategoryRecord"]] >
<blockquote]] > AVAudioSessionCategoryRecord</blockquote]] >
</a]] > ;
NSString *const <a href="file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/com.apple.adc.documentation.AppleiOS6.0.iOSLibrary.docset/Contents/Resources/Documents/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html#//apple_ref/doc/c_ref/AVAudioSessionCategoryPlayAndRecord"]] >
<blockquote]] > AVAudioSessionCategoryPlayAndRecord</blockquote]] >
</a]] > ;
NSString *const <a href="file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/com.apple.adc.documentation.AppleiOS6.0.iOSLibrary.docset/Contents/Resources/Documents/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html#//apple_ref/doc/c_ref/AVAudioSessionCategoryAudioProcessing"]] >
<blockquote]] > AVAudioSessionCategoryAudioProcessing</blockquote]] >
</a]] > ;
NSString *const <a href="file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/com.apple.adc.documentation.AppleiOS6.0.iOSLibrary.docset/Contents/Resources/Documents/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html#//apple_ref/doc/c_ref/AVAudioSessionCategoryMultiRoute"]] >
<blockquote]] > AVAudioSessionCategoryMultiRoute</blockquote]] >
</a]] > ;

1

除了代码的初始化,很重要的一步是对info-plist的设置,让应用支持音频的后台播放

库的引入包括:

AudioToolBox.framework

MediaPlayer.framework

CoreMedia.framework

AVFoundation.framework

后台播放

正常情况下,如果配置了AVAudioSessionCategoryPlayback这个方法并修改了info-plist文件,应用就已经支持后台音频播放了,但是如果每一首歌曲都不存在本地,在网络的话就不行了,需要申请后台任务来进行处理,首先修改:

- (void)applicationDidEnterBackground:(UIApplication *)application {

[application beginReceivingRemoteControlEvents];
}

然后在播放器的播放函数里添加:

-(void)justPlay{

UIBackgroundTaskIdentifier bgTask = 0;

if([UIApplication sharedApplication].applicationState== UIApplicationStateBackground) {

NSLog(@”xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx后台播放”);

[thePlayer play];

UIApplication*app = [UIApplication sharedApplication];

UIBackgroundTaskIdentifier newTask = [app beginBackgroundTaskWithExpirationHandler:nil];

if(bgTask!= UIBackgroundTaskInvalid) {

[app endBackgroundTask: bgTask];

}

bgTask = newTask;

}

else {

NSLog(@”xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx前台播放”);

[thePlayer play];

}

}

这样播放就可以进行前台或者后台的判断,支持网络后台播放了,一首一首连续播放。

Remote控制

在播放视图的ViewController里加上这两个函数:

- (void)viewDidAppear:(BOOL)animated {

NSLog(@”viewDidAppear!!!”);

[super viewDidAppear:animated];

//Once the view has loaded then we can register to begin recieving controls and we can become the first responder

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[self becomeFirstResponder];

}

- (void)viewWillDisappear:(BOOL)animated {

NSLog(@”viewWillDisappear!!!”);

[super viewWillDisappear:animated];

//End recieving events

[[UIApplication sharedApplication] endReceivingRemoteControlEvents];

[self resignFirstResponder];

}

当然也可以同理放到delegate.m里面的进入后台和回到前台的函数中,否则的话,上面的代码只是允许当前视图的情况下进入后台可以Remote控制

然后添加下面的代码:

-(void)remoteControlReceivedWithEvent:(UIEvent *)event{

//if it is a remote control event handle it correctly

if (event.type == UIEventTypeRemoteControl) {

if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) {

[self playerTap];

} else if (event.subtype == UIEventSubtypeRemoteControlNextTrack){

[self nextSongAuto];

[self configNowPlayingInfoCenter];

}

}

}

//Make sure we can recieve remote control events

- (BOOL)canBecomeFirstResponder {

return YES;

}

锁屏封面

一般在每次切换歌曲或者更新信息的时候要调用这个方法

- (void)configNowPlayingInfoCenter {

NSDictionary *albumDic=[currentParserSongArray objectAtIndex:songIndex];

if (NSClassFromString(@”MPNowPlayingInfoCenter”)) {

NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];

[dict setObject:[albumDic objectForKey:@"name"] forKey:MPMediaItemPropertyTitle];

[dict setObject:[albumDic objectForKey:@"singer"] forKey:MPMediaItemPropertyArtist];

[dict setObject:[albumDic objectForKey:@"album"] forKey:MPMediaItemPropertyAlbumTitle];

MPMediaItemArtwork * mArt = [[MPMediaItemArtwork alloc] initWithImage:cdCoverImgView.image];

[dict setObject:mArt forKey:MPMediaItemPropertyArtwork];

[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;

[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];

}

}

打断处理

试用了官方文档上的各种代理方法,打断通知,都没用,后来用C函数处理可以控制打断,首先AudioToolBox.framework是需要引入的

在设定session的时候调用了ASAudioSessionInterruptionListener这个函数 ,就是处理打断的,在所需加入的类的实现

@implementation前面加入这个静态方法

static void ASAudioSessionInterruptionListener(void *inClientData, UInt32 inInterruptionState)

{

[[ToolManager defaultManager] handleInterruption:inInterruptionState];

}

每次打断结束或者开始都会调用这个方法  ,inInterruptionState来判断是开始还是结束,因为是C函数,不可以直接调用类中[self  xxx]方法,通知也没用 ,故写了个单例类,接收这个参数,然后进行判断

- (void)handleInterruptionChangeToState:(NSNotification *)notification

{

AudioQueuePropertyID inInterruptionState=[[notification object] longValue];

if (inInterruptionState == kAudioSessionBeginInterruption)

{

NSLog(@”begin interruption——->”);

}

else if (inInterruptionState == kAudioSessionEndInterruption)

{

NSLog(@”end interruption——->”);

}

}

转载于:https://www.cnblogs.com/Milo-CTO/p/4446318.html

iOS音频的后台播放总结相关推荐

  1. iOS音频的后台播放总结(后台网络请求歌曲,Remote控制,锁屏封面,各种打断)...

    iOS音频的后台播放总结(后台网络请求歌曲,Remote控制,锁屏封面,各种打断) 2013-12-11 21:13 1416人阅读 评论(0) 收藏 举报  分类: cocoa SDK(139)  ...

  2. iOS音频的后台播放 锁屏

    初始化AudioSession和基本配置 音频播放器采用的AVPlayer ,在程序启动的时候需要配置AudioSession,AudioSession负责应用音频的设置,比如支不支持后台,打断等等, ...

  3. iOS从零开始学习直播之音频2.后台播放和在线播放

    本篇主要讲音频的后台播放和在线播放. 后台播放   上一篇写的工程运行之后程序退至后台,发现运行不了,歌停止了,这显然不行,音乐后台播放是标配啊.今天就来讲一下后台播放. 1.在plist文件里,告诉 ...

  4. iOS 音频录制、播放(本地、网络)

    文章目录一.录音机(AVAudioRecorder)1.简介2.如何使用3.具体实现(开始.暂停.停止.播放 四个功能)4.附件实现demo二.播放音频1.播放本地音频文件(AVAudioPlayer ...

  5. iOS音频开发(录音+播放+剪辑+合成+压缩转码)

    录音: //音频会话 AVAudioSession *session = [AVAudioSession sharedInstance]; NSError *sessionError; /* AVAu ...

  6. 当自己视频APP,遇到别人音频APP后台播放音频时候

    当别家音乐APP播放音乐,打开自家视频APP(虽然没有播放视频),但音乐app的音频却暂停了(如果是钉钉语音会议这种情况,会自动退出语音会议). 查了资料:这是音频打断处理问题,举个例子:       ...

  7. android ios av tv,iOS AVPlayer 实现后台连续播放视频

    最近接到一个需求,需要做一个在后台播放视频的功能.折腾了一下,最后总算完成了.因此写一篇文章,介绍下具体的实现步骤,也说说自己遇到的坑,算是总结和记录. 前言 当 App 退到后台时,会进入 susp ...

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

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

  9. iOS 后台播放静音音频保证应用不会被无端杀掉

    由于苹果推送会把一些敏感类消息外流,So 我们采用长连接试的推送服务,网上有此推送的开源项目 传送门在此mpush 此开源项目很好的帮助了国内一些企业对敏感消息推送的保护,但是针对苹果端的推送有一个问 ...

最新文章

  1. Ubuntu、CentOS 解决docker命令权限问题(sudo)
  2. asp.net操作cookie
  3. 机器人水库涵洞检测_2019 届高三上学期期末教学质量检测原创卷 03
  4. xcode 编译时有相同的类,导致冲突,编译错误
  5. ado.net连接mysql 类_C# ADO.NET 连接数据库常用到的类及基本操作格式
  6. linux环境下ntp客户端,多种操作系统NTP客户端配置
  7. datagridview 纵向 横向 合并单元格_每日一Excel技巧(熟能生巧):带公式的单元格,快速批量复制、填充...
  8. oppo面经-java开发
  9. 本周论文推荐 -- 对抗生成网络、知识图谱补全、对话系统、文本生成
  10. 一位平凡毕业生的大学四年
  11. 用DEM制作通用三维地形模型
  12. 【tensorboard】解决ValueError: Duplicate plugins for name projector
  13. Could not find a declaration file for module
  14. 计算机英语第四版可可英语翻译,专四英语作文高分范文背诵(MP3+中英字幕)第28篇:计算机和人翻译...
  15. ssm+java计算机毕业设计公交路线查询系统l1auz(程序+lw+源码+远程部署)
  16. 个人网络信息安全管理方法分享
  17. 云计算与大数据---21大数据张舒
  18. C语言——副作用(side effects)和序列点(sequence points)
  19. 计算机主机为什么漏电,电脑机箱漏电怎么回事
  20. app开发周期需要多久 开发一个app要多长时间

热门文章

  1. MySQL架构设计相关的方式方法和软件介绍
  2. Oracle 收购Sun之后的演义:IBM 和SAP何去何从
  3. [零基础学JAVA]Java SE应用部分-28.Java IO操作(02)
  4. c+oracle+bulk,C#使用OracleBulkCopy
  5. jlpt报名系统显示网络错误和服务器忙,批改网作文提交不了一直显示服务器或网络错误...
  6. springboot整合redis实现分布式锁思想
  7. MATLAB 句柄函数记录——多变量
  8. shell(一)——概述、变量、运算符
  9. overleaf创建表格
  10. mysql binlog c++_关于MySQL的日志管理(binlog)