如何正确处理音频中断

How to properly handle audio interruptions?

本文关键字:中断 音频 正确处理      更新时间:2023-10-16

我创建了一个利用OpenAL进行音频播放的OpenGL 3D游戏,如果在音频设备初始化之前按下"Home"按钮,则会遇到丢失音频的问题。我试图挂接到音频会话中断处理程序,但我的回调从未被调用。无论我是否最小化或最大化我的应用程序。我的"OpenALInterruptionListener"永远不会被调用。

我做错了什么?

AudioSessionInitialize(NULL, NULL, OpenALInterriptionListener, this);
void OpenALInterriptionListener(void * inClientData, UInt32 inInterruptionState)
{
    OpenALDevice * device = (OpenALDevice *) inClientData;
    if (inInterruptionState == kAudioSessionBeginInterruption)
    {
          alcSuspendContext(_context);
          alcMakeContextCurrent(_context);
          AudioSessionSetActive(false);
    }
    else if (inInterruptionState == kAudioSessionEndInterruption)
    {
          UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
          AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
          AudioSessionSetActive(true);    
          alcMakeContextCurrent(_context);
          alcProcessContext(_context);
    }
}

请注意,音频中断和 IOS 目前存在问题。 中断通知很好,但结束音频中断通知并不总是有效。 苹果在这方面有一个错误,他们没有回应。

尝试在 alcMakeContextCurrent(( 中使用 NULL。

void OpenALInterriptionListener(void *inClientData, UInt32 inInterruptionState)
{
    OpenALDevice * device = (OpenALDevice *) inClientData;
    OSStatus nResult;
    if( inInterruptionState == kAudioSessionBeginInterruption )
    {
        alcMakeContextCurrent(NULL);    
    }
    else if( inInterruptionState == kAudioSessionEndInterruption )
    {
        nResult = AudioSessionSetActive(true);
        if( nResult )
        {
            //  "Error setting audio session active"
        }
        alcMakeContextCurrent( device->GetContext() );
    }
}