phone 调用无效后恢复 AVAudioPlayer
Resume AVAudioPlayer after phone call not working
SO 上已经有一些看似相似的问题,但经过数小时的搜索和试验我的代码后,我一直无法找到明确的答案。我能找到的最接近的东西是 this answer,它暗示了 4 年前的 "known bug",但没有详细说明如何解决它。
我有一个 audioPlayer class,它正在使用 AVAudioPlayer 播放音频文件并监听 AVAudioSessionDelegate
方法 beginInterruption
和 endInterruption
。我知道不能保证 endInterruption
所以我在 beginInterruption
中存储了一个布尔值并在 applicationDidBecomeActive
中处理重新启动音频播放。
如果 phone 接到电话但用户拒接或转至语音信箱,这一切都将按预期完美运行。一旦我的应用程序回到活动状态,音频播放就会恢复。
这是我遇到奇怪行为的地方:如果用户接听电话,一旦他们挂断电话似乎 可以按预期工作,但头部phone 或扬声器都没有声音。
我可以通过每秒打印音量和 currentTime 来验证音频在技术上 正在播放 ,但是没有声音。
如果我等了 20-40 秒,音频突然切入并变得清晰可闻,就好像它一直在后台无声播放一样。
经过更多调试后,我注意到 AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint
在这 20-40 秒的静音中保持 true
,然后突然变为 false
并播放音频。
我订阅了 AVAudioSessionSilenceSecondaryAudioHintNotification
以查看是否可以检测到此更改,但它从未被调用,即使 .secondaryAudioShouldBeSilencedHint
从 true
更改为 false
。
我什至在恢复播放音频的方法中尝试显式设置AVAudioSession.sharedInstance().setActive(true)
,但行为没有改变。
最后,我尝试设置一个定时器,在 applicationDidBecomeActive
后将恢复延迟 10 秒,但行为没有改变。
那么,为什么 phone 调用似乎没有将音频会话的控制权交还给我的应用程序?
感谢观看!
代码:
AVAudioSession 设置 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()
}
完成音频后使用它。
AVAudioSession.sharedInstance().setActive(false, withOptions: .NotifyOthersOnDeactivation)
虽然我没有在 setActive
方法中使用任何选项,但我也尝试这样做。
iOS 9.3.1 中似乎有一个错误,在 phone 调用结束后,AVAudioPlayer 不会恢复播放。
以下是为我解决问题的部分片段:(对 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];
});
}
}
}
我在播放器的播放调用中添加了一个小的延迟,它奏效了。
你可以在这里找到我制作的完整演示项目:
https://github.com/liorazi/AVAudioSessionWorkaround
我向 Apple 提交了一个雷达,希望它能在下一个版本中得到修复。
我有同样的问题。尝试在中断后重新加载播放器:
func interruptionNotification(_ notification: Notification) {
guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
return
}
if interruption == .ended && playerWasPlayingBeforeInterruption {
player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
play()
}
}
SO 上已经有一些看似相似的问题,但经过数小时的搜索和试验我的代码后,我一直无法找到明确的答案。我能找到的最接近的东西是 this answer,它暗示了 4 年前的 "known bug",但没有详细说明如何解决它。
我有一个 audioPlayer class,它正在使用 AVAudioPlayer 播放音频文件并监听 AVAudioSessionDelegate
方法 beginInterruption
和 endInterruption
。我知道不能保证 endInterruption
所以我在 beginInterruption
中存储了一个布尔值并在 applicationDidBecomeActive
中处理重新启动音频播放。
如果 phone 接到电话但用户拒接或转至语音信箱,这一切都将按预期完美运行。一旦我的应用程序回到活动状态,音频播放就会恢复。
这是我遇到奇怪行为的地方:如果用户接听电话,一旦他们挂断电话似乎 可以按预期工作,但头部phone 或扬声器都没有声音。
我可以通过每秒打印音量和 currentTime 来验证音频在技术上 正在播放 ,但是没有声音。
如果我等了 20-40 秒,音频突然切入并变得清晰可闻,就好像它一直在后台无声播放一样。
经过更多调试后,我注意到 AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint
在这 20-40 秒的静音中保持 true
,然后突然变为 false
并播放音频。
我订阅了 AVAudioSessionSilenceSecondaryAudioHintNotification
以查看是否可以检测到此更改,但它从未被调用,即使 .secondaryAudioShouldBeSilencedHint
从 true
更改为 false
。
我什至在恢复播放音频的方法中尝试显式设置AVAudioSession.sharedInstance().setActive(true)
,但行为没有改变。
最后,我尝试设置一个定时器,在 applicationDidBecomeActive
后将恢复延迟 10 秒,但行为没有改变。
那么,为什么 phone 调用似乎没有将音频会话的控制权交还给我的应用程序?
感谢观看!
代码:
AVAudioSession 设置 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()
}
完成音频后使用它。
AVAudioSession.sharedInstance().setActive(false, withOptions: .NotifyOthersOnDeactivation)
虽然我没有在 setActive
方法中使用任何选项,但我也尝试这样做。
iOS 9.3.1 中似乎有一个错误,在 phone 调用结束后,AVAudioPlayer 不会恢复播放。
以下是为我解决问题的部分片段:(对 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];
});
}
}
}
我在播放器的播放调用中添加了一个小的延迟,它奏效了。
你可以在这里找到我制作的完整演示项目: https://github.com/liorazi/AVAudioSessionWorkaround
我向 Apple 提交了一个雷达,希望它能在下一个版本中得到修复。
我有同样的问题。尝试在中断后重新加载播放器:
func interruptionNotification(_ notification: Notification) {
guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
return
}
if interruption == .ended && playerWasPlayingBeforeInterruption {
player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
play()
}
}