音频会话中断
- 当有人打来电话时, 音频会话会中断播放音频
- 当电话挂断后, 音频是不会重新开始播放的
- 为了处理这种情况, 可以使用下面的代码
音频会话通知
- AVAudioSession在中断时会发出一个通知 <a>AVAudioSessionInterruptionNotification</a>
- 我们可以通过这个通知来监听音频会话的中断
// 会话中断通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
- 我们使用<a>AVAudioSessionInterruptionType</a>来判断会话的状态
- AVAudioSessionInterruptionTypeBegan: 中断开始
- AVAudioSessionInterruptionTypeEnded: 中断结束
/**
会话中断通知
*/
- (void)handleInterruption:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
if (type == AVAudioSessionInterruptionTypeBegan) {
// 音频会话中断开始, 处理音频中断
}else if (type == AVAudioSessionInterruptionTypeEnded) {
// 音频会话中断结束
}
}
- 会话中断结束后, 我们需要处理音频会话是否已经重新激活, 以及是否可以再次播放音频
- 我们使用<a>AVAudioSessionInterruptionOptions</a>
/**
会话中断通知
*/
- (void)handleInterruption:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
if (type == AVAudioSessionInterruptionTypeBegan) {
// 音频会话中断开始, 处理音频中断
}else if (type == AVAudioSessionInterruptionTypeEnded) {
// 音频会话中断结束, 处理重新播放音频
AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
if (options == AVAudioSessionInterruptionOptionShouldResume) {
// 可以重新播放音频
}
}
}
- 注意: 当音频会话中断并结束中断后, 之前播放的音频是不会自动播放的, 我们需要再次启动播放
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。