|
类别 |
输入 |
输出 |
与iPOD混合 |
遵从静音 |
|
AVAudioSessionCategoryAmbient |
No |
Yes |
Yes |
Yes |
|
AVAudioSessionCategorySoloAmbient |
No |
Yes |
No |
Yes |
|
AVAudioSessionCategoryPlayback |
No |
Yes |
No |
No |
|
AVAudioSessionCategoryRecord |
Yes |
No |
No |
No |
|
AVAudioSessionCategoryPlayAndRecord |
Yes |
Yes |
No |
No |
选中Targets-->Capabilities-->BackgroundModes-->ON, 并勾选Audio and AirPlay选项,如下图
在Appdelegate.m中定义全局变量
UIBackgroundTaskIdentifier _bgTaskId;
-(void)applicationWillResignActive:(UIApplication )application
{
//开启后台处理多媒体事件
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
AVAudioSession session=[AVAudioSession sharedInstance];
[session setActive:YES error:nil];
//后台播放
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
//这样做,可以在按home键进入后台后 ,播放一段时间,几分钟吧。但是不能持续播放网络歌曲,若需要持续播放网络歌曲,还需要申请后台任务id,具体做法是:
_bgTaskId=[AppDelegate backgroundPlayerID:_bgTaskId];
//其中的_bgTaskId是后台任务UIBackgroundTaskIdentifier _bgTaskId;在appdelegate.m中定义的全局变量
}
+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
//设置并激活音频会话类别
AVAudioSession *session=[AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
//允许应用程序接收远程控制
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//设置后台任务ID
UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:backTaskId];
}
return newTaskId;
}
-->在通知中心注册一个事件中断的通知:
//处理中断事件的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterreption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
-->实现接收到中断通知时的方法
//处理中断事件
-(void)handleInterreption:(NSNotification *)sender
{
if(_played)
{
[self.playView.player pause];
_played=NO;
}
else
{
[self.playView.player play];
_played=YES;
}
}iOS- 关于AVAudioSession的使用——后台播放音乐
原文:https://www.cnblogs.com/Free-Thinker/p/9567364.html