草庐IT

ios - 电话不工作后恢复 AVAudioPlayer

coder 2023-09-05 原文

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/

有关ios - 电话不工作后恢复 AVAudioPlayer的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  4. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  5. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  6. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  7. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  8. ruby - JetBrains RubyMine 3.2.4 调试器不工作 - 2

    使用Ruby1.9.2运行IDE提示说需要gemruby​​-debug-base19x并提供安装它。但是,在尝试安装它时会显示消息Failedtoinstallgems.Followinggemswerenotinstalled:C:/ProgramFiles(x86)/JetBrains/RubyMine3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem:Errorinstallingruby-debug-base19x-0.11.30.pre2.gem:The'linecache19'nativegemrequiresinstall

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. ruby - `rescue $!` 是如何工作的? - 2

    我知道全局变量$!包含最新的异常对象,但我对下面的语法感到困惑。谁能帮助我理解以下语法?rescue$! 最佳答案 此构造可防止异常停止您的程序并使堆栈跟踪冒泡。它还会将该异常作为值返回,这很有用。a=get_me_datarescue$!在此行之后,a将保存请求的数据或异常。然后您可以分析该异常并采取相应措施。defget_me_dataraise'Nodataforyou'enda=get_me_datarescue$!puts"Executioncarrieson"pa#>>Executioncarrieson#>>#更现实的

随机推荐