iOS 继续播放或暂时其他app的背景音乐

74 篇文章 0 订阅
66 篇文章 0 订阅

问题:当我们自己开发的应用要使用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

  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值