iOS- 关于AVAudioSession的使用——后台播放音乐

AVAudioSession是一个单例,无需实例化即可直接使用。AVAudioSession在各种音频环境中起着非常重要的作用
•针对不同的音频应用场景,需要设置不同的音频会话分类
 

1.1AVAudioSession的类别  

•AVAudioSessionCategoryAmbient
–混音播放,例如雨声、汽车引擎等,可与其他音乐一起播放
•AVAudioSessionCategorySoloAmbient
–后台播放,其他音乐将被停止
•AVAudioSessionCategoryPlayback
–独占音乐播放
•AVAudioSessionCategoryRecord
–录制音频
•AVAudioSessionCategoryPlayAndRecord
–播放和录制音频
•AVAudioSessionCategoryAudioProcessing
–使用硬件解码器处理音频,该音频会话使用期间,不能播放或录音
 
图解:

类别

输入

输出

与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

 

2.后台播放音乐  

2.1.开启所需要的后台模式  

 

选中Targets-->Capabilities-->BackgroundModes-->ON,
并勾选Audio and AirPlay选项,如下图

2.2.在Appdelegate.m的applicationWillResignActive:方法中激活后台播放,代码如下

 

在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中定义的全局变量
}

2.3.实现一下backgroundPlayerID这个方法  

+(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;
}

2.4.处理中断事件,如电话,微信语音等  原理是,在音乐播放被中断时,暂停播放,在中断完成后,开始播放。具体做法是: 

-->在通知中心注册一个事件中断的通知:
//处理中断事件的通知
[[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;
    }
}
posted @ 2018-08-31 18:27  brave-sailor  阅读(830)  评论(0编辑  收藏  举报