天天看點

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選項,如下圖      
iOS- 關于AVAudioSession的使用——背景播放音樂

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