简体   繁体   中英

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.

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?

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.

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

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

            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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