iOS- 關於AVAudioSession的使用——後臺播放音樂

原文地址:http://www.cnblogs.com/qingche/p/4366335.html


1.前言  

•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.設置後臺任務  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
+ (UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
    // 1. 設置並激活音頻會話類別
       AVAudioSession *session = [AVAudioSession sharedInstance];
    [session AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    // 2. 允許應用程序接收遠程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    // 3. 設置後臺任務ID
      UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
    newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    if (newTaskId != UIBackgroundTaskInvalid && backTaskId != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];
    }
    return newTaskId;
}

2.2.設置後臺播放  

1
2
3
4
5
6
7
//後臺播放音頻設置  
AVAudioSession *session = [AVAudioSession sharedInstance];    
[session setActive:YES error:nil];    
[session setCategory:AVAudioSessionCategoryPlayback error:nil];   
   
//讓app支持接受遠程控制事件  
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];  

 2.3.記錄後臺播放代號  

1
2
3
4
5
// 後臺播放任務Id
UIBackgroundTaskIdentifier  _bgTaskId;
 
// 設置音頻會話,允許後臺播放
_bgTaskId = [SoundTool backgroundPlayerID:_bgTaskId];
發佈了1 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章