IOS-Use of AVAudioSession-playing music in the background, ios-avaudiosession
1. Preface • AVAudioSession is a singleton that can be directly used without instantiation. AVAudioSession plays an important role in various audio environments. • different audio session categories must be set for different audio application scenarios. 1.1AVAudioSession category • AVAudioSessionCategoryAmbient-sound mixing playback, such as rain and car engine, can be played together with other music • AVAudioSessionCategorySoloAmbient-Background playback, other music will be stopped • AVAudioSessionCategoryPlayback-exclusive music play • AVAudioSessionCategoryRecord-recording audio • AVAudioSessionCategoryPlayAndRecord-playing and recording audio • Audio-use a hardware decoder to Process audio during use of this audio session, no playback or recording illustration:
Category |
Input |
Output |
Mixed with iPOD |
Mute compliance |
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. Playing music in the background 2. 1. Set background tasks
+ (UIBackgroundTaskIdentifier) backgroundPlayerID :( UIBackgroundTaskIdentifier) backTaskId {// 1. set and activate the audio session category AVAudioSession * session = [AVAudioSession sharedInstance]; [session AVAudioSessionCategoryPlayback error: nil]; [session setActive: YES error: nil]; // 2. allow applications to receive remote control [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; // 3. set background task ID UIBackgroundTaskIdentifier newTaskId = UBA CkgroundTaskInvalid; newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler: nil]; if (newTaskId! = UIBackgroundTaskInvalid & backTaskId! = UIBackgroundTaskInvalid) {[[UIApplication sharedApplication] endBackgroundTask: backTaskId];} return newTaskId ;}
2. Set background playback
// Set AVAudioSession * session = [AVAudioSession sharedInstance]; [session setActive: YES error: nil]; [session setCategory: AVAudioSessionCategoryPlayback error: nil]; // enable the app to support remote control events [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
2. 3. Record the background playback code
// The background playback task IdUIBackgroundTaskIdentifier _ bgTaskId; // set the audio session to allow backend playback _ bgTaskId = [SoundTool backgroundPlayerID: _ bgTaskId];
Author: Clear Saup
Source: http://www.cnblogs.com/qingche/
The copyright of this article is shared by the author and the blog. You are welcome to repost it, but you must keep this statement and provide a connection to the original article on the article page.