录音被打断的一些处理
会话设置
- (void)setupAudioSession {
self.audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
// 设置音频会话类别
[self.audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionDefaultToSpeaker
error:&error];
if (error) {
[self handleError:error];
return;
}
// 设置音频会话模式
[self.audioSession setMode:AVAudioSessionModeDefault error:&error];
if (error) {
[self handleError:error];
return;
}
// 激活音频会话
[self.audioSession setActive:YES error:&error];
if (error) {
[self handleError:error];
return;
}
}
监听通知处理
- (void)registerForNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleInterruption:)
name:AVAudioSessionInterruptionNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleRouteChange:)
name:AVAudioSessionRouteChangeNotification
object:nil];
}
- (void)handleInterruption:(NSNotification *)notification {
NSDictionary *info = notification.userInfo;
AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
switch (type) {
case AVAudioSessionInterruptionTypeBegan: {
// 记录当前录音为打断状态 暂停当前录音
break;
}
case AVAudioSessionInterruptionTypeEnded: {
AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
if (options & AVAudioSessionInterruptionOptionShouldResume) {
// 如果之前在录音,此处尝试恢复录音
}
break;
}
}
}
- (void)handleRouteChange:(NSNotification *)notification {
NSDictionary *info = notification.userInfo;
AVAudioSessionRouteChangeReason reason = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];
switch (reason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: {
// 音频路由发生变化(如插入/拔出耳机),重新配置音频会话
[self setupAudioSession];
break;
}
default:
break;
}
}
#pragma mark - Error Handling
- (void)handleError:(NSError *)error {
//加一些处理 弹窗或者提示
}
结束录音时应该释放当前音频会话, 给别的应用去使用,一般来说都应该如此,不然很可能出现被打断恢复不了的情况,就算你监听了打断恢复的通知,没人发通知给你也是白瞎 ,
这句代码相当于发通知
[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
未经作者授权,禁止转载
本文来自博客园,作者:CoderWGB,转载请注明原文链接:https://www.cnblogs.com/wgb1234/p/18621966
THE END
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2020-12-22 (私)一些个人的配置备份(工作备用)