后臺錄音時音頻會話響應中斷(開始中斷)大致分為以下幾種情況:
- 鬧鐘或日歷鬧鐘響起或
- 當來電話時。
- 他應用程序激活其音頻會話時。
中斷結束 :應用程序繼續運行,要恢復音頻,必須重新啟動音頻會話。
如果用戶忽略呼叫或關閉鬧鐘,則系統發出“中斷已結束”消息,
audio_session_interrupted_2x.png
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_observerApplicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
- (void)_observerApplicationWillResignActive:(NSNotification *)sender {
if ([sender.name isEqualToString:UIApplicationWillResignActiveNotification]) {
[self _registerNotificationForAudioSessionInterruption];
}
} - (void)_registerNotificationForAudioSessionInterruption {
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(_audioSessionInterruptionHandle:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
} - (void)_audioSessionInterruptionHandle:(NSNotification *)sender {
if ([sender.userInfo[AVAudioSessionInterruptionTypeKey] intValue] == AVAudioSessionInterruptionTypeBegan) {
//pause session
} else if ([sender.userInfo[AVAudioSessionInterruptionTypeKey] intValue] == AVAudioSessionInterruptionTypeEnded) {
//Continue
}
} - (void)_observerApplicationBecomeActiveAction:(NSNotification *)sender {
if ([sender.name isEqualToString:UIApplicationWillEnterForegroundNotification]) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
}
}
在dealloc 中移除通知會出現異常, 對象生命周期文檔中明確說明 dealloc 方法不可super 不可調用,不要調用其他對象的方法。在此調用移除通知的監聽 會導致 鬧鐘響起時彈出通知欄,關閉通知之后無法調起app 繼續進行錄音操作,斷點debug代碼已經執行。我分析的原因是后臺錄音權限申請之后iOS系統會 管理app 當在AVAudioSessionInterruptionTypeEnded 時重啟錄音,首先是 此監聽在dealloc 中移除,而在通知欄彈出通知的一瞬間,系統并未回收app,只是進入休眠狀態。還在內存中只是無法重新啟動錄音。而未在dealloc中移除監聽,系統會重新打開app 進入錄音頁面,這樣就不存在中斷監聽被移除,可以繼續錄音。我選擇在app 進入前臺時移除后臺中app 錄音中斷的監聽,在頁面消失移除所有通知監聽。
歡迎大家指正。