电话无法恢复后恢复AVAudioPlayer

时间:2016-04-16 10:30:36

标签: ios iphone swift ios9 avaudioplayer

在SO上已经有一些看似相似的问题,但经过几个小时的搜索和试验我的代码,我一直无法找到明确的答案。我能找到的最接近的是this answer,它暗示了一个已知的错误" 4年前,但没有详细说明如何解决它。

我有一个audioPlayer类,它正在播放AVAudioPlayer的音频文件,并在监听AVAudioSessionDelegate方法beginInterruptionendInterruption。我知道endInterruption不能保证,所以我在beginInterruption中存储了一个布尔值并处理applicationDidBecomeActive中的音频重放。

如果手机接到电话并且用户拒绝或让它转到语音信箱,这一切都可以正常运行。一旦我的应用程序返回活动状态,音频播放就会恢复。

我在这里发现奇怪的行为:如果用户接听电话,一旦他们挂机,所有似乎按预期工作,但耳机或扬声器都没有声音。

我可以通过每秒打印音量和当前时间来验证音频在技术上播放,但声音不会出现。

如果我等待20-40秒,音频会突然切入并听到声音,好像它已经在后台默默播放。

经过更多调试后,我注意到AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint在这20-40秒的静音中保持true,然后突然变为false并让音频播放。

我订阅了AVAudioSessionSilenceSecondaryAudioHintNotification以查看是否可以检测到此更改,但即使.secondaryAudioShouldBeSilencedHinttrue更改为false,也永远不会被调用。

我甚至在恢复播放音频的方法中尝试显式设置AVAudioSession.sharedInstance().setActive(true),但行为没有改变。

最后,我尝试设置一个计时器,以便在applicationDidBecomeActive之后将恢复延迟10秒,但行为没有改变。

那么,为什么电话似乎没有放弃对我的应用程序的音频会话的控制?

谢谢你看看!

代码:

init()中的AVAudioSession设置:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.handleAudioHintChange), name: AVAudioSessionSilenceSecondaryAudioHintNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.handleAudioInterruption), name: AVAudioSessionInterruptionNotification, object: nil)

do {
  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)
  print("AVAudioSession Category Playback OK")
  do {
    try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation)
    print("AVAudioSession is Active")
  } catch let error as NSError {
    print(error.localizedDescription)
  }
} catch let error as NSError {
  print(error.localizedDescription)
}

通知处理程序:

///////////////////////////////////
// This never gets called :( //////

func handleAudioHintChange(notification: NSNotification) {
  print("audio hint changed")
}
///////////////////////////////////

func handleAudioInterruption(notification: NSNotification) {
  if notification.name != AVAudioSessionInterruptionNotification || notification.userInfo == nil{
    return
  }

  if let typeKey = notification.userInfo [AVAudioSessionInterruptionTypeKey] as? UInt,
  let type = AVAudioSessionInterruptionType(rawValue: typeKey) {
    switch type {
      case .Began:
        print("Audio Interruption Began")
        NSUserDefaults.standardUserDefaults().setBool(true, forKey:"wasInterrupted")

      case .Ended:
        print("Audio Interuption Ended")
    }
  }
}

App代表:

func applicationDidBecomeActive(application: UIApplication) {
  if(NSUserDefaults.standardUserDefaults().boolForKey("wasInterrupted")) {
    audioPlayer.resumeAudioFromInterruption()
  }
}

重启功能:

// This works great if the phone call is declined
func resumeAudioFromInterruption() {
  NSUserDefaults.standardUserDefaults().removeObjectForKey("wasInterrupted")
  do {
    try AVAudioSession.sharedInstance().setActive(true)
    print("AVAudioSession is Active")
  } catch let error as NSError {
    print(error.localizedDescription)
  }
  thisFunctionPlaysMyAudio()

}

3 个答案:

答案 0 :(得分:5)

虽然我没有使用setActive方法中的任何选项,但我也尝试过这样做。

iOS 9.3.1中似乎有一个错误,在电话结束后,它无法恢复播放AVAudioPlayer。

以下是为我解决的问题:(对不起,Objective-C)

- (void)handleInterruption:(NSNotification *) notification{
    if (notification.name != AVAudioSessionInterruptionNotification || notification.userInfo == nil) {
        return;
    }

    NSDictionary *info = notification.userInfo;

    if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {

        if ([[info valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeBegan]]) {
            NSLog(@"InterruptionTypeBegan");
        } else {
            NSLog(@"InterruptionTypeEnded");

            //*The* Workaround - Add a small delay to the avplayer's play call; Without the delay, the playback will *not* be resumed
            //
            //(I didn't play much with the times, but 0.01 works with my iPhone 6S 9.3.1)
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                NSLog(@"playing");
                [_player play];
            });
        }
    }
}

我在播放器的播放通话中添加了一个小延迟,但它确实有效。

你可以找到我在这里制作的完整演示项目: https://github.com/liorazi/AVAudioSessionWorkaround

我向Apple提交了一个雷达,希望它能在下一个版本中得到修复。

答案 1 :(得分:0)

完成音频后使用此功能。

AVAudioSession.sharedInstance()。setActive(false,withOptions:.NotifyOthersOnDeactivation)

答案 2 :(得分:0)

我有同样的问题。尝试在中断后重新加载播放器:

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