AVAudioSession Interruptions

2019-02-08 13:15发布

So in my app, running on iOS 6, everything seems to work fine with audio. I use the old C API format to catch interruptions using a callback; setting up via: AudioSessionInitialize(NULL, NULL, interruptionListenerCallback, (__bridge void *)self) and it was great. Using iOS 7 SDK though, it seems that my interruption callback is never called when the device receives calls or an alarm goes off.

After some looking around, I heard that the old C api were deprecated and that you should move to the newer AVAudioSession functions. More reading revealed that the AVAudioSession delegate is deprecated and that you should use the NSNotification for AVAudioSessionInterruptionNotification to catch interruptions and do whatever needs to be done.

For me, it seems that this notification is never actually fired and therefore I never get properly interrupted, which then breaks all of my audio stuff after the call ends.

I sign up for the notification like so:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AudioInterruption:) name:AVAudioSessionInterruptionNotification object:nil];

For now, the AudioInterruption: function simply logs that it got fired. Neither the log nor any breakpoints are triggering.

To be clear, initially audio playback and recording works fine. When an interruption occurs (such as an incoming call or an alarm), no interruption notification is fired. If more surrounding code is necessary, let me know.

3条回答
何必那么认真
2楼-- · 2019-02-08 13:59

Do you have an AVCaptureSession instance in your application?
If that is the case, I would suggest the same answer that I received for my linked question:
Try to set NO to the usesApplicationAudioSession property of your AVCaptureSession instance.
It is a property available since iOS 7. In the previous iOS versions, each AVCaptureSession made use of a private AVAudioSession. Since iOS 7, the Capture Sessions make use of the shared application's AVAudioSession.
The usesApplicationAudioSession property is enabled by default, so if you want to keep the old behavior you must disable it, by setting NO.

I hope this will work for you as well.

查看更多
狗以群分
3楼-- · 2019-02-08 14:18

You didn’t pass the AVAudioSession instance in your addObserver call as the last parameter.

Try this:

AVAudioSession *session = [AVAudioSession sharedInstance];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(AudioInterruption:)
                                             name:AVAudioSessionInterruptionNotification
                                           object:session];
查看更多
Lonely孤独者°
4楼-- · 2019-02-08 14:19

For me, activating audio session and adding observer when user actually push play button has resolved the issue; notification was fired. I think apple doc say something about that here.

查看更多
登录 后发表回答