【问题标题】:AVAudioSession can't play sound after app re-becomes active应用重新激活后 AVAudioSession 无法播放声音
【发布时间】:2014-11-29 13:12:06
【问题描述】:

所以我有一个音乐应用程序,它使用 AVAudioSession 允许它在后台播放。我用这个电话:

[audioSession setActive:YES
            withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                  error:nil];

我现在的问题是,如果我转到另一个应用程序并且它窃取了音频会话(因此现在停止从我的应用程序播放音乐并播放其他内容),然后我回到我的应用程序,无论我做什么来重置我的音频会话或我的音频单元,我的应用程序的声音消失了。

有人知道该怎么做吗?

【问题讨论】:

  • 您在处理AVAudioSessionInterruptionNotification 吗?
  • 不,我需要在那个通知处理程序中做什么?只是 setActive:NO?
  • 我想现在我可以在我的音频会话被打断之前做一些事情,但是问题仍然存在..

标签: ios core-audio avaudiosession


【解决方案1】:

所以在注册了 AVAudioSession 通知之后:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(handleAudioSessionInterruption:)
                                             name:AVAudioSessionInterruptionNotification
                                           object:aSession]; 

你需要恢复/重启你需要重启你的播放器在处理程序中断类型是AVAudioSessionInterruptionTypeEnded:

- (void)handleAudioSessionInterruption:(NSNotification*)notification {

    NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
    NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];

    switch (interruptionType.unsignedIntegerValue) {
        case AVAudioSessionInterruptionTypeBegan:{
            // • Audio has stopped, already inactive
            // • Change state of UI, etc., to reflect non-playing state
        } break;
        case AVAudioSessionInterruptionTypeEnded:{
            // • Make session active
            // • Update user interface
            // • AVAudioSessionInterruptionOptionShouldResume option
            if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                // Here you should continue playback.
                [player play];
            }
        } break;
        default:
            break;
    }
}

你可以在这里看到完整的解释:AVplayer resuming after incoming call

【讨论】:

  • AVAudioSessionInterruptionTypeBegan 的部分让我在返回应用程序时恢复声音,但AVAudioSessionInterruptionTypeEnded 的部分永远不会被调用。我想这取决于中断的应用程序通知调度?另外,请注意,我没有使用 AVAudioPlayer/AVPlayer
  • 你如何测试这个?是什么触发了中断?
  • 1.从我的应用程序播放音乐。 2.离开应用程序,转到音乐应用程序,在那里播放一些音乐(来自我的应用程序的音乐停止,委托中断开始方法被调用,来自音乐应用程序的音乐开始)。 3. 在音乐应用中停止音乐(不调用委托中断结束方法)
  • 那我不知道怎么了,对不起。它应该工作。我发现了这个:stackoverflow.com/questions/7406389/…。也许他们所说的错误仍未修复,尽管我对此表示怀疑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多