音乐播放器-中断处理 - (Obj-C)

当手机突然来电话时,音乐播放不会自动停止,避免影响接听电话,我们还需要手动做中断处理

最早的打算处理是通过AVAudioPlayer的AVAudioPlayerDelegate代理方法实现,中断相关的代理方法有:

- (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);

目前已经过期,在API中会提示使用AVAudioSession代替

/* AVAudioPlayer INTERRUPTION NOTIFICATIONS ARE DEPRECATED - Use AVAudioSession instead. */

点进AVAudioSession中,翻到最下面的找到AVAudioSessionDelegate代理方法

#pragma mark -- AVAudioSessionDelegate protocol --
/* The AVAudioSessionDelegate protocol is deprecated. Instead you should register for notifications. */
__TVOS_PROHIBITED
@protocol AVAudioSessionDelegate 
@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

协议注释中提到AVAudioSessionDelegate protocol也过期了,建议我们使用notifications

接下来就通过通知的方式,对音乐播放器做打断处理

回到之前封装的音乐播放工具类,在init方法中添加监听通知

// 监听事件中断通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:nil];

在监听到中断事件通知时,通过通知中的
notification.userInfo[AVAudioSessionInterruptionOptionKey]的Value可以判断当前中断的开始和结束,Value为NSNumber类型,所以判断时需要转为本数据类型

当中断开始时,停止播放
当中断结束时,继续播放

// 监听中断通知调用的方法
- (void)audioSessionInterruptionNotification:(NSNotification *)notification{
    
    /*
         监听到的中断事件通知,AVAudioSessionInterruptionOptionKey
     
         typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionType)
         {
             AVAudioSessionInterruptionTypeBegan = 1, 中断开始
             AVAudioSessionInterruptionTypeEnded = 0,  中断结束
         }

     */
    
    int type = [notification.userInfo[AVAudioSessionInterruptionOptionKey] intValue];
    
    switch (type) {
        case AVAudioSessionInterruptionTypeBegan: // 被打断
            [self.audioPlayer pause]; // 暂停播放
            break;
        case AVAudioSessionInterruptionTypeEnded: // 中断结束
            [self.audioPlayer play];  // 继续播放
            break;
        default:
            break;
    }
}

你可能感兴趣的:(音乐播放器-中断处理 - (Obj-C))