iOS音频-AVAudioSession

作者 : 开心源码 本文共7555个字,预计阅读时间需要19分钟 发布时间: 2022-05-12 共121人阅读

最近在解决录音方面的问题,做个转载
参考链接
参考链接

AVAudioSession就是用来管理多个APP对音频硬件设施(麦克风,扬声器)的资源使用。

举例一下AVAudioSession可以做这些事情

  • 设置自己的APP能否和其余APP音频同时存在,还是中断其余APP声音
  • 在手机调到静音模式下,自己的APP音频能否可以播放出声音
  • 电话或者者其余APP中断自己APP的音频的事件解决
  • 指定音频输入和输出的设施(比方是听筒输出声音,还是扬声器输出声音)
  • 能否支持录音,录音同时能否支持音频播放

AVAudioSession Category

AVAudioSession的接口比较简单。APP启动的时候会自动激活AVAudioSession,当然我们可以手动激活代码如下。

//导入头文件#import <AVFoundation/AVFoundation.h>//AVAudioSession是一个单例类AVAudioSession *session = [AVAudioSession sharedInstance];//AVAudioSessionCategorySoloAmbient是系统默认的category[session setCategory:AVAudioSessionCategorySoloAmbient error:nil];//激活AVAudioSession[session setActive:YES error:nil];

可以看到设置session这里有两个参数,category和options
Category iOS下目前有七种,每种Category都对应能否支持下面四种能力

  • Interrupts non-mixable apps audio:能否打断不支持混音播放的APP

  • Silenced by the Silent switch:能否会响应手机静音键开关

  • Supports audio input:能否支持音频录制

  • Supports audio output:能否支持音频播放

    Category能否允许音频播放/录音能否打断其余不支持混音APP能否会被静音键或者锁屏键静音
    AVAudioSessionCategoryAmbient支持否是
    AVAudioSessionCategoryAudioProcessing不支持播放,不支持录制是否
    AVAudioSessionCategoryPlayback只支持播放默认YES,可以重写为NO否
    AVAudioSessionCategoryRecord只支持录制是否(锁屏下仍可录制)
    AVAudioSessionCategorySoloAmbient只支持播放是是
    AVAudioSessionCategoryMultiRoute支持播放,支持录制是否
    AVAudioSessionCategoryPlayAndRecord支持播放,支持录制默认YES,可以重写为NO否
  • AVAudioSessionCategoryAmbient,只支持音频播放。这个 Category,音频会被静音键和锁屏键静音。并且不会打断其余应用的音频播放。

  • AVAudioSessionCategorySoloAmbient,这个是系统默认使用的 Category,只支持音频播放。音频会被静音键和锁屏键静音。和AVAudioSessionCategoryAmbient不同的是,这个会打断其余应用的音频播放

  • AVAudioSessionCategoryPlayback,只支持音频播放。你的音频不会被静音键和锁屏键静音。适用于音频是主要功能的APP,像网易云这些音乐app,锁屏后仍然可以播放。

需要注意一下,选择支持在静音键切到静音状态以及锁屏键切到锁屏状态下依然可以播放音频 Category 时,必需在应用中开启支持后端音频功能,详见 UIBackgroundModes。
  • AVAudioSessionCategoryRecord,只支持音频录制。不支持播放。
  • AVAudioSessionCategoryPlayAndRecord,支持音频播放和录制。音频的输入和输出不需要同步进行,也可以同步进行。需要音频通话类应用,可以使用这个 Category。
  • AVAudioSessionCategoryAudioProcessing,只支持本地音频编解码解决。不支持播放和录制。
  • AVAudioSessionCategoryMultiRoute,支持音频播放和录制。允许多条音频流的同步输入和输出。(比方USB连接外部扬声器输出音频,蓝牙耳机同时播放另一路音频这种特殊需求)

可以通过AVAudioSession的属性来读取当前设施支持的Category

@property(readonly) NSArray<NSString *> *availableCategories;

设置Category代码

NSError *setCategoryError = nil;BOOL isSuccess = [[AVAudioSession sharedInstance]         setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];if (!success) { //这里可以读取setCategoryError.localizedDescription查看错误起因}

AVAudioSession Mode&&Options

刚刚详情的Category定义了七种主场景,实际开发需求中有时候需要对Category进行微调整,我们发现这个接口还有两个参数Mode和Options。

AVAudioSession Mode

我们通过读取下面这条属性获取当前设施支持的Mode

@property(readonly) NSArray<NSString *> *availableModes;

iOS下有七种mode来定制我们的Category行为

模式兼容的场景
AVAudioSessionModeDefaultAll默认模式
AVAudioSessionModeVoiceChatAVAudioSessionCategoryPlayAndRecordVoIP
AVAudioSessionModeGameChatAVAudioSessionCategoryPlayAndRecord游戏录制,GKVoiceChat自动设置
AVAudioSessionModeVideoRecordingAVAudioSessionCategoryPlayAndRecord AVAudioSessionCategoryRecord录制视频
AVAudioSessionModeMoviePlaybackAVAudioSessionCategoryPlayback视频播放
AVAudioSessionModeMeasurementAVAudioSessionCategoryPlayAndRecord AVAudioSessionCategoryRecord AVAudioSessionCategoryPlayback最小系统
AVAudioSessionModeVideoChatAVAudioSessionCategoryPlayAndRecord视频通话

下面逐一详情下每个Mode

  • AVAudioSessionModeDefault,默认模式,与所有的 Category 兼容

  • AVAudioSessionModeVoiceChat,适用于VoIP 类型的应用。只能是 – AVAudioSessionCategoryPlayAndRecord Category下。在这个模式系统会自动配置AVAudioSessionCategoryOptionAllowBluetooth 这个选项。系统会自动选择最佳的内置麦克风组合支持语音聊天。

  • AVAudioSessionModeVideoChat,用于视频聊天类型应用,只能是 AVAudioSessionCategoryPlayAndRecord Category下。适在这个模式系统会自动配置 AVAudioSessionCategoryOptionAllowBluetooth 和 AVAudioSessionCategoryOptionDefaultToSpeaker 选项。系统会自动选择最佳的内置麦克风组合支持视频聊天。

  • AVAudioSessionModeGameChat,适用于游戏类应用。使用 GKVoiceChat 对象的应用会自动设置这个模式和 AVAudioSessionCategoryPlayAndRecord Category。实际参数和AVAudioSessionModeVideoChat一致

  • AVAudioSessionModeVideoRecording,适用于使用摄像头采集视频的应用。只能是 AVAudioSessionCategoryPlayAndRecord 和 AVAudioSessionCategoryRecord 这两个 Category下。这个模式搭配 AVCaptureSession API 结合来用可以更好地控制音视频的输入输出路径。(例如,设置 automaticallyConfiguresApplicationAudioSession 属性,系统会自动选择最佳输出路径。

  • AVAudioSessionModeMeasurement,最小化系统。只用于 AVAudioSessionCategoryPlayAndRecord、AVAudioSessionCategoryRecord、AVAudioSessionCategoryPlayback 这几种 Category。

  • AVAudioSessionModeMoviePlayback,适用于播放视频的应用。只用于 AVAudioSessionCategoryPlayback 这个Category。

AVAudioSession Options

我们还可以使用options去微调Category行为,如下表

OptionOption功能说明兼容的 Category
AVAudioSessionCategoryOptionMixWithOthers支持和其余APP音频 mixAVAudioSessionCategoryPlayAndRecord AVAudioSessionCategoryPlayback AVAudioSessionCategoryMultiRoute
AVAudioSessionCategoryOptionDuckOthers系统智能调低其余APP音频音量AVAudioSessionCategoryPlayAndRecord AVAudioSessionCategoryPlayback AVAudioSessionCategoryMultiRoute
AVAudioSessionCategoryOptionAllowBluetooth支持蓝牙音频输入AVAudioSessionCategoryRecord AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryOptionDefaultToSpeaker设置默认输出音频到扬声器AVAudioSessionCategoryPlayAndRecord

调优我们的Category

通过Category和合适的Mode和Options的搭配我们可以调优出我们的效果,下面举两个应用场景:

用过高德地图的都知道,在后端播放QQ音乐的时候,假如导航语音出来,QQ音乐不会中止,而是被智能压低和混音,等导航语音播报完后,QQ音乐正常播放,这里我们需要后端播放音乐,所以Category使用AVAudioSessionCategoryPlayback,需要混音和智能压低其余APP音量,所以Options选用 AVAudioSessionCategoryOptionMixWithOthers和AVAudioSessionCategoryOptionDuckOthers

BOOL isSuccess = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback         withOptions:AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDuckOthers error:&setCategoryError];

音频中断解决

中断发生时,应用程序的AVAudioSession会发送通知AVAudioSessionInterruptionNotification,注册通知代码如下:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];

在接收到通知的userInfo中,会包含一个AVAudioSessionInterruptionTypeKey,用来标识中断开始和中断结束.
当中断类型为AVAudioSessionInterruptionTypeKeyEnded时,userInfo中还会包含一个AVAudioSessionInterruptionOptions来表明音频会话能否已经重新激活以及能否可以再次播放.示例代码如下:

- (void)handleInterruption:(NSNotification *)notification{  _descriptionLabel.text = @"handleInterruption";NSDictionary *info = notification.userInfo;AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];if (type == AVAudioSessionInterruptionTypeBegan) {    //Handle InterruptionBegan}else{    AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];    if (options == AVAudioSessionInterruptionOptionShouldResume) {        //Handle Resume            }  }}

在iOS设施上增加或者移除音频输入,输出线路时,会发生线路改变,比方客户插入耳机或者断开USB麦克风.当这些事件发生时,音频会根据情况改变输入或者输入线路,同时AVAudioSession会发送一个相关变化的通知AVAudioSessionRouteChangeNotification.注册通知的相关代码如下:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];

根据苹果公司的文档,当客户插入耳机时,隐含的意思是客户不希望外界听到具体的音频了内容,这就意味着当客户断开耳机时,播放的内容可能需要保密,所以我们需要在断开耳机时中止音频播放.

AVAudioSessionRouteChangeNotification通知的userinfo中会带有通知发送的起因信息及前一个线路的形容.线路变更的起因保存在userinfo的AVAudioSessionRouteChangeReasonKey值中,通过返回值可以推断出不同的事件,对于旧音频设施中断对应的reason为AVAudioSessionRouteChangeReasonOldDeviceUnavailable.但光凭这个reason并不能断定是耳机断开,所以还需要使用通过AVAudioSessionRouteChangePreviousRouteKey取得上一线路的形容信息,注意线路的形容信息整合在一个输入NSArray和一个输出NSArray中,数组中的元素都是AVAudioSessionPortDescription对象.我们需要从线路形容中找到第一个输出接口并判断其能否为耳机接口,假如为耳机,则中止播放.

- (void)handleRouteChange:(NSNotification *)notification{NSDictionary *info = notification.userInfo;AVAudioSessionRouteChangeReason reason =       [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];if (reason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {  //旧音频设施断开//获取上一线路形容信息AVAudioSessionRouteDescription *previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey];//获取上一线路的输出设施类型AVAudioSessionPortDescription *previousOutput = previousRoute.outputs[0];NSString *portType = previousOutput.portType;if ([portType isEqualToString:AVAudioSessionPortHeadphones]) {    }  }}
总结:AVAudioSession的作用就是管理音频这一唯一硬件资源的分配,通过调优合适的AVAudioSession来适配我们的APP对于音频的功能需求。切换音频场景时候,需要相应的切换AVAudioSession。

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » iOS音频-AVAudioSession

发表回复