我们在做软件开发的时候 会产生很多需求
就音乐播放器而言 我们需要后台播放 这是最基本的需求
当我们正放着音乐 有事儿要做则要将音乐放到后台播放
当我们再打开软件的时候音乐还可以继续播放 并不影响我们的使用
我们播放音乐的时候 可以同时启动了两个音乐播放器
但是如果两个音乐播放器同时播放音乐的话 那么会产生一些混合音
会造成很杂乱的声音 这个我们也可以设置
可以设置音乐播放的分类
下面是苹果给开发者提供的一些 方法
我们可以根据自己的需求 选择使用
#pragma mark -- Values for the category property --
/* Use this category for background sounds such as rain, car engine noise, etc.
Mixes with other music. */
AVF_EXPORT NSString *const AVAudioSessionCategoryAmbient;
/* Use this category for background sounds. Other music will stop playing. */
AVF_EXPORT NSString *const AVAudioSessionCategorySoloAmbient;
/* Use this category for music tracks.*/
AVF_EXPORT NSString *const AVAudioSessionCategoryPlayback;
/* Use this category when recording audio. */
AVF_EXPORT NSString *const AVAudioSessionCategoryRecord;
/* Use this category when recording and playing back audio. */
AVF_EXPORT NSString *const AVAudioSessionCategoryPlayAndRecord;
/* Use this category when using a hardware codec or signal processor while
not playing or recording audio. */
AVF_EXPORT NSString *const AVAudioSessionCategoryAudioProcessing;
下面讲一下 后台播放音乐的基本方法
首先 我们要在 代理里面告诉它 我们要开启后台任务
- (void)applicationDidEnterBackground:(UIApplication *)application {
//开启后台任务,让程序保持运行状态
[application beginBackgroundTaskWithExpirationHandler:nil];
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
然后我们要在info.plist 中添加音乐播放类型
最后我们要设置会话类型
+(void)initialize
{
_soundIDDict = [NSMutableDictionary dictionary];
_audioPlayDict = [NSMutableDictionary dictionary];
//设置音频会话类型
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategorySoloAmbient error:nil];
[session setActive:YES error:nil];
}