【问题标题】:Pause AVAudioPlayer when external audio is playing播放外部音频时暂停 AVAudioPlayer
【发布时间】:2018-09-29 10:45:16
【问题描述】:

我目前面临一个问题,如果你们中的一些人能解决这个问题并想出一个简单的解决方案,我会很高兴。

所以基本上,问题是: 当一些外部声音进来时,我有什么方法可以暂停正在进行的 AVAudioPlayer:音乐、来电、通知等。

我知道,对于检测呼叫,有一个新的 CXCallObserverDelegate 可以帮助我们,但是对于音乐和其余部分,是否有任何简单的解决方案可以解决所有这些问题?

就代码而言,一切正常,播放音频没有任何问题。我有一个自定义路径和一个错误,错误返回 nil。

NSError *avPlayerError = nil; NSData* mp3Data = [[NSData alloc] initWithContentsOfFile: path options: NSDataReadingMappedIfSafe error: &avPlayerError];

【问题讨论】:

  • 请说明您进行了哪些研究,您已经尝试过哪些内容,哪些无效,代码示例等。请阅读How to Askminimal reproducible example 然后edit 您的问题显示演示问题的最小代码。

标签: ios avaudioplayer


【解决方案1】:

我正在将此代码用于我的应用程序:

在 AppDelegate 中,didFinishLaunchingWithOptions 为任何传入中断添加观察者

NotificationCenter.default.addObserver(self, selector: #selector(self.onAudioSessionEvent(noti:)), name: Notification.Name.AVAudioSessionInterruption, object: nil)

当任何中断发生时,该函数将被调用

@objc func onAudioSessionEvent(noti:Notification){
    if noti.name == Notification.Name.AVAudioSessionInterruption
    {
        if let value = noti.userInfo![AVAudioSessionInterruptionTypeKey] as? NSNumber {
            if value.uintValue == AVAudioSessionInterruptionType.began.rawValue {
                print("start interrupt")


            }else{
                print("end interrupt")

            }
        }
    }
}

【讨论】:

  • 感谢您的回答!我会试试的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
相关资源
最近更新 更多