简体   繁体   English

播放外部音频时暂停 AVAudioPlayer

[英]Pause AVAudioPlayer when external audio is playing

I'm currently facing a problem and I'll be glad if some of you being trough this problem and came up with a simple solution.我目前正面临一个问题,如果你们中的一些人遇到了这个问题并提出了一个简单的解决方案,我会很高兴。

So basically, the question is: Is there any way that I can pause an ongoing AVAudioPlayer when some external sounds come in such as: music, incoming call, notifications, etc.所以基本上,问题是:当一些外部声音进入时,我有什么方法可以暂停正在进行的 AVAudioPlayer,例如:音乐、来电、通知等。

I know that for detecting a call, there's this new CXCallObserverDelegate that helps us, but for music and the rest is there any simple solution to resolve all of this?我知道为了检测呼叫,有这个新的 CXCallObserverDelegate 可以帮助我们,但是对于音乐和其余部分,是否有任何简单的解决方案来解决所有这些问题?

In terms of code, everything works fine, there's not a single problem regarding playing the audio.在代码方面,一切正常,播放音频没有任何问题。 I have a custom path and an error, the error returns nil.我有一个自定义路径和一个错误,错误返回 nil。

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

i'm using this code for my application :我正在将此代码用于我的应用程序:

in AppDelegate , didFinishLaunchingWithOptions add Observer for any incoming interrupt在 AppDelegate 中, didFinishLaunchingWithOptions为任何传入中断添加观察者

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

When any interrupt occurs this function will called当任何中断发生时,这个函数将被调用

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

            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM