应用打断事件处理

  • app播放声音被打断处理
    - (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player此方法在iOS8已经废弃
    /* AVAudioPlayer INTERRUPTION NOTIFICATIONS ARE DEPRECATED - Use AVAudioSession instead. */

  • 改用 AVAudioSession 通知AVAudioSessionInterruptionNotification

文档信息

/* Registered listeners will be notified when the system has interrupted the audio session and when
 the interruption has ended.  Check the notification's userInfo dictionary for the interruption type -- either begin or end.
 In the case of an end interruption notification, check the userInfo dictionary for AVAudioSessionInterruptionOptions that
 indicate whether audio playback should resume.
 */

  • 播放声音的时候注册通知
    // 注册打断通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AVAudioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:session];
  • 实现方法
// 接收通知方法
  - (void)AVAudioSessionInterruptionNotification: (NSNotification *)notificaiton {
      NSLog(@"%@", notificaiton.userInfo);
  }

打电话 测试 打印出 AVAudioSessionInterruptionTypeKey = 1

/* keys for AVAudioSessionInterruptionNotification */
    /* value is an NSNumber representing an AVAudioSessionInterruptionType */

typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionType)
{
    AVAudioSessionInterruptionTypeBegan = 1,  /* the system has interrupted your audio session */
    AVAudioSessionInterruptionTypeEnded = 0,  /* the interruption has ended */
} NS_AVAILABLE_IOS(6_0);
  • 可以通过通知信息中的type 来做不同的操作
// 接收通知方法
- (void)AVAudioSessionInterruptionNotification: (NSNotification *)notificaiton {
    NSLog(@"%@", notificaiton.userInfo);
    
    AVAudioSessionInterruptionType type = [notificaiton.userInfo[AVAudioSessionInterruptionTypeKey] intValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        [self.player pause];
    } else {
        [self.player play];
    }
}

这样 当有电话打进来 就会停止播放,挂断电话继续播放

你可能感兴趣的:(应用打断事件处理)