2013-12-23 3 views

ответ

7

AVAudioSession отправит уведомление, когда прерывание начнется и закончится. См Handling Audio Interruptions

- (id)init 
{ 
    if (self = [super init]) { 
     [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 

     NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; 
     [center addObserver:self selector:@selector(audioSessionInterrupted:) name:AVAudioSessionInterruptionNotification object:nil]; 
    } 
} 

- (void)audioSessionInterrupted:(NSNotification *)notification 
{ 
    int interruptionType = [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue]; 
    if (interruptionType == AVAudioSessionInterruptionTypeBegan) { 
     if (_state == GBPlayerStateBuffering || _state == GBPlayerStatePlaying) { 
      NSLog(@"Pausing for audio session interruption"); 
      pausedForAudioSessionInterruption = YES; 
      [self pause]; 
     } 
    } else if (interruptionType == AVAudioSessionInterruptionTypeEnded) { 
     if ([notification.userInfo[AVAudioSessionInterruptionOptionKey] intValue] == AVAudioSessionInterruptionOptionShouldResume) { 
      if (pausedForAudioSessionInterruption) { 
       NSLog(@"Resuming after audio session interruption"); 
       [self play]; 
      } 
     } 
     pausedForAudioSessionInterruption = NO; 
    } 
} 
+0

мы можем использовать CTCallCenter для этого – user2889249

+0

я бы не советовал, потому что CTCallCenter AVAudioSession обеспечивает более детальный интерфейс. Я обновил свой ответ, чтобы удалить устаревшие методы. –

54

Начиная с прошивкой 6 вы должны обращаться с AVAudioSessionInterruptionNotification и AVAudioSessionMediaServicesWereResetNotification, перед этим вы должны были использовать методы делегата.

Сначала вы должны позвонить в одноэлементный AVAudioSession и настроить его для вашего желаемого использования.

Например:

AVAudioSession *aSession = [AVAudioSession sharedInstance]; 
[aSession setCategory:AVAudioSessionCategoryPlayback 
      withOptions:AVAudioSessionCategoryOptionAllowBluetooth 
       error:&error]; 
[aSession setMode:AVAudioSessionModeDefault error:&error]; 
[aSession setActive: YES error: &error]; 

Тогда вы должны реализовать два метода, для уведомлений, которые AVAudioSession бы назвали:

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(handleAudioSessionInterruption:) 
              name:AVAudioSessionInterruptionNotification 
              object:aSession]; 

Первый для любого перерыва, который будет называться из-за входящий вызов, будильник и т. д.

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(handleMediaServicesReset) 
              name:AVAudioSessionMediaServicesWereResetNotification 
              object:aSession]; 

Второй, если мед Сброс сервера ia по какой-либо причине, вы должны обработать это уведомление, чтобы перенастроить звук или сделать домашнее хозяйство. Кстати, словарь уведомлений не будет содержать никаких объектов.

Вот пример для обработки прерывания воспроизведения:

- (void)handleAudioSessionInterruption:(NSNotification*)notification { 

    NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey]; 
    NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey]; 

    switch (interruptionType.unsignedIntegerValue) { 
     case AVAudioSessionInterruptionTypeBegan:{ 
      // • Audio has stopped, already inactive 
      // • Change state of UI, etc., to reflect non-playing state 
     } break; 
     case AVAudioSessionInterruptionTypeEnded:{ 
      // • Make session active 
      // • Update user interface 
      // • AVAudioSessionInterruptionOptionShouldResume option 
      if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) { 
       // Here you should continue playback. 
       [player play]; 
      } 
     } break; 
     default: 
      break; 
    } 
} 

Обратите внимание, что вы должны возобновить воспроизведение, когда дополнительное значение AVAudioSessionInterruptionOptionShouldResume

И для другого уведомления вы должны позаботиться о следующем:

- (void)handleMediaServicesReset { 
// • No userInfo dictionary for this notification 
// • Audio streaming objects are invalidated (zombies) 
// • Handle this notification by fully reconfiguring audio 
} 

С уважением.

+0

В документации говорится, что «при выполнении MediaServicesWereReset« выполните соответствующие шаги для повторной инициализации любых аудио-объектов, используемых вашим приложением », просто переконфигурируйте AudioSession и верните его в Active. что мне еще нужно делать? – xialin

1

В некоторых случаях мой AVPlayer не возобновляет воспроизведение, даже если я звоню play(). Только перезарядка игрок помогает мне решить эту проблему:

func interruptionNotification(_ notification: Notification) { 
    guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt, 
     let interruption = AVAudioSessionInterruptionType(rawValue: type) else { 
     return 
    } 
    if interruption == .ended && playerWasPlayingBeforeInterruption { 
     player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url)) 
     play() 
    } 
    } 
Смежные вопросы