后臺(tái)錄音時(shí)音頻會(huì)話(huà)響應(yīng)中斷(開(kāi)始中斷)大致分為以下幾種情況:
- 鬧鐘或日歷鬧鐘響起或
- 當(dāng)來(lái)電話(huà)時(shí)。
- 他應(yīng)用程序激活其音頻會(huì)話(huà)時(shí)。
中斷結(jié)束 :應(yīng)用程序繼續(xù)運(yùn)行,要恢復(fù)音頻,必須重新啟動(dòng)音頻會(huì)話(huà)。
如果用戶(hù)忽略呼叫或關(guān)閉鬧鐘,則系統(tǒng)發(fā)出“中斷已結(jié)束”消息,
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 中移除通知會(huì)出現(xiàn)異常, 對(duì)象生命周期文檔中明確說(shuō)明 dealloc 方法不可super 不可調(diào)用,不要調(diào)用其他對(duì)象的方法。在此調(diào)用移除通知的監(jiān)聽(tīng) 會(huì)導(dǎo)致 鬧鐘響起時(shí)彈出通知欄,關(guān)閉通知之后無(wú)法調(diào)起app 繼續(xù)進(jìn)行錄音操作,斷點(diǎn)debug代碼已經(jīng)執(zhí)行。我分析的原因是后臺(tái)錄音權(quán)限申請(qǐng)之后iOS系統(tǒng)會(huì) 管理app 當(dāng)在A(yíng)VAudioSessionInterruptionTypeEnded 時(shí)重啟錄音,首先是 此監(jiān)聽(tīng)在dealloc 中移除,而在通知欄彈出通知的一瞬間,系統(tǒng)并未回收app,只是進(jìn)入休眠狀態(tài)。還在內(nèi)存中只是無(wú)法重新啟動(dòng)錄音。而未在dealloc中移除監(jiān)聽(tīng),系統(tǒng)會(huì)重新打開(kāi)app 進(jìn)入錄音頁(yè)面,這樣就不存在中斷監(jiān)聽(tīng)被移除,可以繼續(xù)錄音。我選擇在app 進(jìn)入前臺(tái)時(shí)移除后臺(tái)中app 錄音中斷的監(jiān)聽(tīng),在頁(yè)面消失移除所有通知監(jiān)聽(tīng)。
歡迎大家指正。