ios - 电话不工作后恢复 AVAudioPlayer

标签 ios iphone swift ios9 avaudioplayer

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

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

如果手机接到电话但用户拒接或转至语音信箱,这一切都将按预期完美运行。一旦我的应用回到事件状态,音频播放就会恢复。

这里是我遇到奇怪行为的地方:如果用户接听电话,一旦他们挂断电话,一切似乎都会按预期工作但是耳机或扬声器都没有声音。

我可以通过每秒打印音量和 currentTime 来验证音频在技术上播放,但声音没有发出。

如果我等了 20-40 秒,音频突然切入并变得清晰可闻,就好像它一直在后台无声地播放一样。

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

我订阅了 AVAudioSessionSilenceSecondaryAudioHintNotification 以查看是否可以检测到此更改,但它从未被调用,即使 .secondaryAudioShouldBeSilencedHinttrue 更改> 为 false

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

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

那么,为什么电话似乎没有将 Audio Session 的控制权交还给我的应用程序?

感谢您的关注!


代码:

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

应用委托(delegate):

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

最佳答案

虽然我没有在 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 提交了一个雷达,希望它能在下一个版本中得到修复。

关于ios - 电话不工作后恢复 AVAudioPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36662959/

相关文章:

iphone - 如何读取麦克风输入?

ios - 呈现 VC 时出现问题,屏幕变黑

objective-c - 为什么复制指针以解决 ARC 下基于 block 的保留循环是有意义的?

ios - 如何根据发送日期订购用户消息以供显示?

iOS:在 UITableViewCintroller 子类中创建默认静态表

ios - 为什么标签栏项目只显示没有图标的标题?

swift - 为什么 iPhone 不将数组传输到 Apple Watch?

ios - 当我上下滚动时,UITableView 按钮和标签被删除

iOS Deep linking and Universal link,如何在ios中进行深度链接

iphone - 删除 CAKeyframeAnimation 不会释放内存