當(dāng)手機(jī)突然來(lái)電話時(shí),音樂(lè)播放不會(huì)自動(dòng)停止,避免影響接聽(tīng)電話,我們還需要手動(dòng)做中斷處理
最早的打算處理是通過(guò)AVAudioPlayer的AVAudioPlayerDelegate代理方法實(shí)現(xiàn),中斷相關(guān)的代理方法有:
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player NS_DEPRECATED_IOS(2_2, 8_0);
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags NS_DEPRECATED_IOS(6_0, 8_0);
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withFlags:(NSUInteger)flags NS_DEPRECATED_IOS(4_0, 6_0);
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player NS_DEPRECATED_IOS(2_2, 6_0);
目前已經(jīng)過(guò)期,在API中會(huì)提示使用AVAudioSession代替
/* AVAudioPlayer INTERRUPTION NOTIFICATIONS ARE DEPRECATED - Use AVAudioSession instead. */
點(diǎn)進(jìn)AVAudioSession中,翻到最下面的找到AVAudioSessionDelegate代理方法
#pragma mark -- AVAudioSessionDelegate protocol --
/* The AVAudioSessionDelegate protocol is deprecated. Instead you should register for notifications. */
__TVOS_PROHIBITED
@protocol AVAudioSessionDelegate <NSObject>
@optional
- (void)beginInterruption; /* something has caused your audio session to be interrupted */
/* the interruption is over */
- (void)endInterruptionWithFlags:(NSUInteger)flags NS_AVAILABLE_IOS(4_0); /* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */
- (void)endInterruption; /* endInterruptionWithFlags: will be called instead if implemented. */
/* notification for input become available or unavailable */
- (void)inputIsAvailableChanged:(BOOL)isInputAvailable;
@end
協(xié)議注釋中提到AVAudioSessionDelegate protocol也過(guò)期了,建議我們使用notifications
接下來(lái)就通過(guò)通知的方式,對(duì)音樂(lè)播放器做打斷處理
回到之前封裝的音樂(lè)播放工具類,在init方法中添加監(jiān)聽(tīng)通知
// 監(jiān)聽(tīng)事件中斷通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:nil];
在監(jiān)聽(tīng)到中斷事件通知時(shí),通過(guò)通知中的
notification.userInfo[AVAudioSessionInterruptionOptionKey]的Value可以判斷當(dāng)前中斷的開(kāi)始和結(jié)束,Value為NSNumber類型,所以判斷時(shí)需要轉(zhuǎn)為本數(shù)據(jù)類型
當(dāng)中斷開(kāi)始時(shí),停止播放
當(dāng)中斷結(jié)束時(shí),繼續(xù)播放
// 監(jiān)聽(tīng)中斷通知調(diào)用的方法
- (void)audioSessionInterruptionNotification:(NSNotification *)notification{
/*
監(jiān)聽(tīng)到的中斷事件通知,AVAudioSessionInterruptionOptionKey
typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionType)
{
AVAudioSessionInterruptionTypeBegan = 1, 中斷開(kāi)始
AVAudioSessionInterruptionTypeEnded = 0, 中斷結(jié)束
}
*/
int type = [notification.userInfo[AVAudioSessionInterruptionOptionKey] intValue];
switch (type) {
case AVAudioSessionInterruptionTypeBegan: // 被打斷
[self.audioPlayer pause]; // 暫停播放
break;
case AVAudioSessionInterruptionTypeEnded: // 中斷結(jié)束
[self.audioPlayer play]; // 繼續(xù)播放
break;
default:
break;
}
}