音頻會話中斷
- 當(dāng)有人打來電話時, 音頻會話會中斷播放音頻
- 當(dāng)電話掛斷后, 音頻是不會重新開始播放的
- 為了處理這種情況, 可以使用下面的代碼
音頻會話通知
- AVAudioSession在中斷時會發(fā)出一個通知 <a>AVAudioSessionInterruptionNotification</a>
- 我們可以通過這個通知來監(jiān)聽音頻會話的中斷
// 會話中斷通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
- 我們使用<a>AVAudioSessionInterruptionType</a>來判斷會話的狀態(tài)
- AVAudioSessionInterruptionTypeBegan: 中斷開始
- AVAudioSessionInterruptionTypeEnded: 中斷結(jié)束
/**
會話中斷通知
*/
- (void)handleInterruption:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
if (type == AVAudioSessionInterruptionTypeBegan) {
// 音頻會話中斷開始, 處理音頻中斷
}else if (type == AVAudioSessionInterruptionTypeEnded) {
// 音頻會話中斷結(jié)束
}
}
- 會話中斷結(jié)束后, 我們需要處理音頻會話是否已經(jīng)重新激活, 以及是否可以再次播放音頻
- 我們使用<a>AVAudioSessionInterruptionOptions</a>
/**
會話中斷通知
*/
- (void)handleInterruption:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
if (type == AVAudioSessionInterruptionTypeBegan) {
// 音頻會話中斷開始, 處理音頻中斷
}else if (type == AVAudioSessionInterruptionTypeEnded) {
// 音頻會話中斷結(jié)束, 處理重新播放音頻
AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
if (options == AVAudioSessionInterruptionOptionShouldResume) {
// 可以重新播放音頻
}
}
}
- 注意: 當(dāng)音頻會話中斷并結(jié)束中斷后, 之前播放的音頻是不會自動播放的, 我們需要再次啟動播放
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。