系统来电打断录音,如何捕获 kAudioSessionProperty_InterruptionType 并恢复?
解读
国内 iOS 面试中,音视频场景是“基础能力+工程经验”的双重考点。
面试官抛出“来电打断录音”这一高频异常,目的有三:
- 验证候选人是否真正踩过真机坑,还是只跑过模拟器;
- 考察对 AudioSession 生命周期与 Runtime 回调线程的掌握;
- 观察候选人能否把“打断-恢复”做成可灰度、可埋点、可容灾的线上代码,而非 Demo 级玩具。
因此,回答必须给出:
- 注册与注销时机(防止野指针与重复注册);
- 区分 Begin/End 两种 InterruptionType;
- 主线程同步 UI 与录音线程状态;
- 恢复时重新配置 AudioSession、AVAudioRecorder 文件句柄、Meter 计时器;
- 容错:飞行模式、双卡切换、微信语音、CarPlay 等场景下的二次打断。
知识点
- AudioSession 与 AVAudioSession
前者是 C API,后者是 Objective-C 封装;iOS 7 之后官方推荐 AVAudioSession,但底层仍走 AudioSession。 - kAudioSessionProperty_InterruptionType → AVAudioSessionInterruptionTypeBegan/Ended
NSNotification 名:AVAudioSessionInterruptionNotification,userInfo 中 AVAudioSessionInterruptionTypeKey 值为 NSNumber(int)。 - 线程模型
系统回调在任意线程,UI 刷新必须切回主线程;录音线程(一般自建 serial queue)需原子标记 isRecording,防止 race。 - 恢复路径
Ended 后必须 setActive:YES 并重新激活 AudioSession,否则后续 start 失败 error.code=561015905(AVAudioSessionErrorCodeCannotStartRecording)。 - 文件续写
AVAudioRecorder 不支持断点续写,需手动关闭旧文件并新建文件,或改用 AudioQueue/AudioUnit 自行管理 PCM 缓存。 - 内存与泄漏
通知中心未移除、block 循环引用、AudioSession 未置 inactive,都会导致后台被杀或电量异常,国内厂商埋点会抓“录音泄漏”。
答案
// RecorderManager.h
@interface RecorderManager : NSObject
+ (instancetype)shared;
- (void)startRecord;
- (void)stopRecord;
@end
// RecorderManager.m
#import <AVFoundation/AVFoundation.h>
@interface RecorderManager ()
@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, strong) NSURL *recordURL;
@property (nonatomic, assign) BOOL isRecording;
@property (nonatomic, strong) dispatch_queue_t recordQueue;
@end
@implementation RecorderManager
+ (instancetype)shared {
static RecorderManager *m;
static dispatch_once_t once;
dispatch_once(&once, ^{ m = [[self alloc] init]; });
return m;
}
- (instancetype)init {
self = [super init];
if (self) {
_recordQueue = dispatch_queue_create("com.demo.record", DISPATCH_QUEUE_SERIAL);
[self setupAudioSession];
[self addNotification];
}
return self;
}
- (void)setupAudioSession {
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error = nil;
[session setCategory:AVAudioSessionCategoryPlayAndRecord
mode:AVAudioSessionModeDefault
options:AVAudioSessionCategoryOptionDefaultToSpeaker
error:&error];
if (error) NSLog(@"setCategory error:%@", error);
}
- (void)addNotification {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleInterruption:)
name:AVAudioSessionInterruptionNotification
object:[AVAudioSession sharedInstance]];
}
- (void)handleInterruption:(NSNotification *)note {
UInt8 type = [note.userInfo[AVAudioSessionInterruptionTypeKey] intValue];
BOOL wasSuspended = [note.userInfo[AVAudioSessionInterruptionOptionKey] intValue] & AVAudioSessionInterruptionOptionShouldResume;
if (type == AVAudioSessionInterruptionTypeBegan) {
dispatch_async(self.recordQueue, ^{
if (self.isRecording) {
[self.recorder pause]; // 暂停而非 stop,保留句柄
self.isRecording = NO;
dispatch_async(dispatch_get_main_queue(), ^{
// 埋点:录音被打断
});
}
});
}
else if (type == AVAudioSessionInterruptionTypeEnded) {
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error = nil;
[session setActive:YES error:&error];
if (error) {
NSLog(@"session active error:%@", error);
return;
}
if (wasSuspended) {
dispatch_async(self.recordQueue, ^{
// 新建文件避免旧文件损坏
[self.recorder stop];
self.recorder = [self createNewRecorder];
BOOL ok = [self.recorder prepareToRecord] && [self.recorder record];
if (ok) {
self.isRecording = YES;
dispatch_async(dispatch_get_main_queue(), ^{
// 埋点:录音自动恢复
});
}
});
}
}
}
- (AVAudioRecorder *)createNewRecorder {
NSString *fileName = [NSString stringWithFormat:@"%.0f.m4a", [[NSDate date] timeIntervalSince1970]];
self.recordURL = [[self recordFolderURL] URLByAppendingPathComponent:fileName];
NSDictionary *setting = @{AVFormatIDKey:@(kAudioFormatMPEG4AAC),
AVSampleRateKey:@44100,
AVNumberOfChannelsKey:@1,
AVEncoderAudioQualityKey:@(AVAudioQualityHigh)};
NSError *error = nil;
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:self.recordURL settings:setting error:&error];
if (error) NSLog(@"create recorder error:%@", error);
return recorder;
}
- (NSURL *)recordFolderURL {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [paths.firstObject stringByAppendingPathComponent:@"records"];
[[NSFileManager defaultManager] createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
return [NSURL fileURLWithPath:folder];
}
- (void)startRecord {
dispatch_async(self.recordQueue, ^{
if (self.isRecording) return;
self.recorder = [self createNewRecorder];
BOOL ok = [self.recorder prepareToRecord] && [self.recorder record];
self.isRecording = ok;
});
}
- (void)stopRecord {
dispatch_async(self.recordQueue, ^{
if (!self.isRecording) return;
[self.recorder stop];
self.isRecording = NO;
// 返回文件路径供业务层上传
});
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
// 注意:单例不会走 dealloc,但模板代码需保留,防止被误用
}
@end
关键细节:
- 使用 serial queue 保证 recorder 状态串行化,避免竞争。
- 恢复时重新创建 AVAudioRecorder,防止旧文件写入异常。
- setActive:YES 必须在 Ended 后立刻调用,否则 record 失败。
- 通知中心注册在单例初始化完成,避免重复 addObserver 崩溃。
拓展思考
- 双卡来电与 VoLTE
国内运营商双卡切换会触发二次 interruption,间隔仅 200 ms,需做 0.5 s 防抖,防止频繁创建文件。 - 蓝牙手环/车载 CarPlay
路由变化会伴随 AVAudioSessionRouteChangeNotification,需联合判断:若 routeChangeReason == NewDeviceAvailable 且当前处于 interruption,则延迟 1 s 再恢复,避免硬件冲突。 - 合规埋点
工信部 164 号文要求录音前弹窗授权,打断恢复后若用户未点击“继续”按钮,不得自动恢复,需业务层介入状态机。 - 性能敏感模块
新闻采访类 App 采用 AudioQueue + 环形缓冲区,打断时只标记写入偏移,恢复后无缝续写同一文件,减少文件碎片与上传分片压力。 - 与 Swift 混编
若工程已迁 Swift,需在 Objective-C 暴露中断状态回调 block,供 Swift 层调用,避免在 Swift 再注册一次通知造成双倍回调。