问题描述
关于SO已经存在一些看似相似的问题,但是经过数小时的搜索和试验我的代码后,我仍然找不到清晰的答案.我能找到的最接近的东西是这个答案,它暗示了4年前的已知错误",但没有详细说明解决方法.
There are some seemingly similar questions already on SO, but after hours of searching and experimenting with my code, I have been unable to find a clear answer. The closest thing I could find was this answer which alludes to a "known bug" 4 years ago, but does not elaborate on how to address it.
我有一个audioPlayer类,该类正在使用AVAudioPlayer播放音频文件并侦听AVAudioSessionDelegate
方法beginInterruption
和endInterruption
.我知道不能保证endInterruption
,所以我在beginInterruption
中存储了一个布尔值,并在applicationDidBecomeActive
中处理了重新开始音频播放的问题.
I have an audioPlayer class that is playing an audio file with AVAudioPlayer and listening for the AVAudioSessionDelegate
methods beginInterruption
and endInterruption
. I know that endInterruption
is not guaranteed so I store a boolean in beginInterruption
and handle restarting the audio playback in applicationDidBecomeActive
.
如果电话收到呼叫并且用户拒绝或允许其转到语音邮件,则所有这些都可以按预期完美地工作.我的应用恢复到活动状态后,音频就会立即恢复播放.
This all works perfectly as expected if the phone receives a call and the user declines it or lets it go to voicemail. As soon as my app goes back into the active state, audio playback resumes.
这是我发生奇怪行为的地方:如果用户接听呼叫,一旦他们挂断了所有似乎即可正常工作但是没有声音通过耳机或扬声器发出.
Here's where I'm getting weird behavior: If the user answers the call, once they hang up everything seems to work as expected but no sound comes out through either the headphones or the speakers.
我可以每秒打印一次音量和currentTime来验证音频在技术上是正在播放,但是声音不会发出.
I can verify that the audio is technically playing by printing its volume and currentTime every second, but the sound isn't coming out.
如果我等待20-40秒,音频突然切入并可以听见,就像在后台静默播放一样.
If I wait for 20-40 seconds, the audio suddenly cuts in and becomes audible, as if it had been silently playing in the background.
经过更多调试后,我注意到AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint
保持true
沉默了20-40秒,然后突然变为false
并开始播放音频.
After more debugging, I noticed that AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint
remains true
for these 20-40 seconds of silence, before suddenly changing to false
and letting the audio play.
我订阅了AVAudioSessionSilenceSecondaryAudioHintNotification
来查看是否可以检测到此更改,但是即使.secondaryAudioShouldBeSilencedHint
从true
更改为false
,也从未被调用.
I subscribed to the AVAudioSessionSilenceSecondaryAudioHintNotification
to see if I could detect this change, but it never gets called, even when .secondaryAudioShouldBeSilencedHint
changes from true
to false
.
我什至在恢复音频播放的方法中明确尝试了 设置AVAudioSession.sharedInstance().setActive(true)
,但是行为没有改变.
I even tried explicitly setting AVAudioSession.sharedInstance().setActive(true)
in the method that resumes playback of the audio, but the behavior did not change.
最后,我尝试设置计时器以将applicationDidBecomeActive
之后的恢复时间延迟10秒,但是行为没有改变.
Lastly, I tried setting a timer to delay the resume for 10 seconds after applicationDidBecomeActive
, but the behavior did not change.
那么,为什么电话似乎没有放弃对音频会话的控制权回到我的应用程序?
感谢您的光临!
代码:
init()
中的AVAudioSession设置:
AVAudioSession setup in init()
:
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")
}
}
}
应用代理:
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
方法中未使用任何选项,但我还是尝试做同样的事情.
I tried to do the same, although I didn't use any options in the setActive
method.
iOS 9.3.1中似乎存在一个错误,该错误在通话结束后无法恢复AVAudioPlayer的播放.
There seem to be a bug in iOS 9.3.1 that doesn't resume playback of the AVAudioPlayer after the phone call ends.
以下是为我解决的代码段:(对Objective-C表示抱歉)
Here is a snippet of what solved it for me: (Sorry for the 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];
});
}
}
}
我在播放器的通话中增加了一点延迟,并且奏效了.
I added a small delay to the player's play call, and it worked.
您可以在此处找到我制作的完整演示项目: https://github.com/liorazi/AVAudioSessionWorkaround
You can find the full Demo project I made here:https://github.com/liorazi/AVAudioSessionWorkaround
我向Apple提交了雷达,希望它在下一个版本中得到解决.
I submitted a radar to Apple, hopefully it'll get fixed on the next release.
这篇关于电话无法正常工作后恢复AVAudioPlayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!