1、持有AVAudioSession的类添加AVAudioSessionInterruptionNotification监听音频中断状态:
(电话、闹铃等归结为一般性的中断,由AVAudioSessionInterruptionNotification通知)
监听回调中userInfo包含AVAudioSessionInterruptionTypeKey,key所对应的枚举值分别为:
typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionType)
{
//中断开始
AVAudioSessionInterruptionTypeBegan =1, /* the system has interrupted your audio session */
//中断结束
AVAudioSessionInterruptionTypeEnded =0, /* the interruption has ended */
};
2、持有AVAudioSession的类添加AVAudioSessionSilenceSecondaryAudioHintNotification监听音频中断状态:
(其他App占用session 导致中断,由AVAudioSessionSilenceSecondaryAudioHintNotification通知)
监听回调中userInfo包含AVAudioSessionSilenceSecondaryAudioHintTypeKey,key所对应的枚举值分别为:
typedef NS_ENUM(NSUInteger, AVAudioSessionSilenceSecondaryAudioHintType)
{
//其他App占用session
AVAudioSessionSilenceSecondaryAudioHintTypeBegin =1, /* the system is indicating that another application's primary audio has started */
//其他App释放session
AVAudioSessionSilenceSecondaryAudioHintTypeEnd =0, /* the system is indicating that another application's primary audio has stopped */
};
3、持有AVAudioSession的类添加AVAudioSessionRouteChangeNotification监听:
(外设改变,由AVAudioSessionRouteChangeNotification通知)
监听回调中userInfo包含AVAudioSessionRouteChangeReasonKey,key所对应的枚举值分别为:
typedef NS_ENUM(NSUInteger, AVAudioSessionRouteChangeReason)
{
//未知原因
AVAudioSessionRouteChangeReasonUnknown =0,
//有新设备可用
AVAudioSessionRouteChangeReasonNewDeviceAvailable =1,
//旧设备不可用
AVAudioSessionRouteChangeReasonOldDeviceUnavailable =2,
//category改变
AVAudioSessionRouteChangeReasonCategoryChange =3,
//App重置了输出设置
AVAudioSessionRouteChangeReasonOverride =4,
//从睡眠中唤醒
AVAudioSessionRouteChangeReasonWakeFromSleep =6,
//当前category下没有可用的设备
AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory =7,
//Router的配置改变
AVAudioSessionRouteChangeReasonRouteConfigurationChange =8// added in iOS 7
};
不同的音频播放类,中断处理不同:
System Sound Services: 系统自动处理,中断开始:静音,中断结束:继续播放
AVFoundation:AVAudioPlayer/AVAudioRecord在中断开始时会自动暂停,需记录暂停位置、时间等信息,中断结束后需要调用播放方法并设置时间为上次暂停的时间才能继续播放。
AVAudioSession下的其他监听:
AVAudioSessionMediaServicesWereLostNotification 监听媒体服务器丢失/连接不上
AVAudioSessionMediaServicesWereResetNotification 监听媒体服务器重启
**注意点**
1)有中断开始的通知,不一定有中断结束的通知,需要监听App重新进入前台的状态
2)不论什么方式播放音频,一定是电话优先,来电话的情况下其他音频中断
3)AVAudioSession可监听外设音频状态(例如耳机)