问题:当我们自己开发的应用要使用AVAudioSession时,可能会中断其它应用的音乐播放,例如:QQ音乐,酷我音乐等?
解决方案:当我们自己开发的应用播放时,暂停其他应用的播放,当我们的应用播放完毕时,继续其他应用的播放,实现代码如下
#import "VLAudioSessionControl.h"
#import <AVFoundation/AVFoundation.h>
@implementation VLAudioSessionControl
/*
* 继续播放后台背景音乐, 取消激活当前应用的audio session
* @param error 设置失败时的错误信息
**/
+ (void)resumeBackgroundSoundWithError:(NSError **)error {
//Deactivate audio session in current app
//Activate audio session in others' app depending on wether they listen to the Category changed
//See here https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioGuidelinesByAppType/AudioGuidelinesByAppType.html#//apple_ref/doc/uid/TP40007875-CH11-SW1
[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:error];
}
/*
* 暂停后台背景音乐的播放,激活当前应用的audio
* @param error 设置失败时的错误信息
**/
+ (void)pauseBackgroundSoundWithError:(NSError **)error {
//See here https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/ConfiguringanAudioSession/ConfiguringanAudioSession.html#//apple_ref/doc/uid/TP40007875-CH2-SW1
AVAudioSession *session = [AVAudioSession sharedInstance];
//Set AVAudioSessionCategoryPlayback category mode for current app
[session setCategory:AVAudioSessionCategoryPlayback error:error];
//Activate audio session in current app
//Deactivate audio session in others' app
[session setActive:YES error:error];
}
+ (void)pauseBackgroundSoundWithCategoryRecord {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryRecord error:nil];
[session setActive:YES error:nil];
}
@end
请注意:
1.Category的选择,取决于在你激活你的应用的audio session时,下一步要录音还是播放,如果录音的话,一定要设置category为AVAudioSessionCategoryRecord
如果是播放,那就设置AVAudioSessionCategoryPlayback
2.如果你准备要录音,而你设置成了AVAudioSessionCategoryPlayback你可以会得到一个意想不到的的结果Unexpected error or warning