iOS- 關於AVAudioSession的使用——後台播放音樂,ios-avaudiosession

來源:互聯網
上載者:User

iOS- 關於AVAudioSession的使用——後台播放音樂,ios-avaudiosession
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.設定背景工作  
+ (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.設定後台播放  
//後台播放音頻設定  AVAudioSession *session = [AVAudioSession sharedInstance];    [session setActive:YES error:nil];    [session setCategory:AVAudioSessionCategoryPlayback error:nil];     //讓app支援接受遠端控制事件  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];  
 2.3.記錄後台播放代號  
// 後台播放任務IdUIBackgroundTaskIdentifier  _bgTaskId;// 設定音頻會話,允許後台播放_bgTaskId = [SoundTool backgroundPlayerID:_bgTaskId];

 

 

 

作者: 清澈Saup
出處: http://www.cnblogs.com/qingche/
本文著作權歸作者和部落格園共有,歡迎轉載,但必須保留此段聲明,且在文章頁面明顯位置給出原文串連。

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.