iOS中后台重新获取麦克风权限

5

我试图在应用程序后台时获取麦克风。我正在使用音频单元技术并能够在后台录制音频。但是一旦我的AudioSession被中断,我就无法在应用程序在后台时重新启动AudioSession。 注意:如果应用程序在前台,我可以重新启动AudioSession。 以下是与中断对应的代码:

- (void) beginInterruption {
    [[AVAudioSession sharedInstance] setActive:NO error:&error];
    AudioOutputUnitStop(m_audioUnit);
}
- (void) endInterruptionWithFlags:(NSUInteger) flags{
    [[AVAudioSession sharedInstance] setActive:YES error:&error];
    AudioOutputUnitStart(m_audioUnit);
}

与音频会话设置相对应的代码

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:&error];

与AudioUnit对应的代码

// Describe audio component
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_RemoteIO;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;

// Get component
AudioComponent inputComponent = AudioComponentFindNext(NULL, &desc);

// Get audio units
oserr = AudioComponentInstanceNew(inputComponent, &m_audioUnit);
checkStatus(oserr);

// Enable IO for recording
UInt32 flag = 1;
oserr = AudioUnitSetProperty(m_audioUnit,
                             kAudioOutputUnitProperty_EnableIO,
                             kAudioUnitScope_Input,
                             1,
                             &flag,
                             sizeof(flag));
checkStatus(oserr);

UInt32 enableOutput        = 0;    // to disable output
AudioUnitElement outputBus = 0;

// Disable output
oserr = AudioUnitSetProperty (
                              m_audioUnit,
                              kAudioOutputUnitProperty_EnableIO,
                              kAudioUnitScope_Output,
                              outputBus,
                              &enableOutput,
                              sizeof (enableOutput)
                              );
checkStatus(oserr);

oserr = AudioUnitInitialize(m_audioUnit);

oserr = AudioOutputUnitStart(m_audioUnit);

大多数流行的录音应用似乎不支持此功能,即使是iOS自带的“语音备忘录”在启动Siri时也会被中断。

以下是我在EndInterruption中遇到的错误: AUIOClient_StartIO失败(-12985) AURemoteIO :: ChangeHardwareFormats:错误-10875

有人成功从后台重新获取麦克风吗?


有趣的问题。我之前没有测试过,但是现在我看到了同样的问题。 - Lewis Gordon
你知道“-12985”实际上是什么意思吗?我也见过它,但在任何头文件中都找不到它。 - robbie_c
1个回答

4

在添加了以下内容后,我成功地解决了问题:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

viewDidAppear方法中。感谢这篇文章MPMoviePlayerController / AVAudioSession in background doesn't restart play after incoming call,但我不清楚如何在此处使用beginReceivingRemoteControlEvents方法对AudioSession产生影响。
另一个重要的观察结果是,无论您接听/拒绝电话,都会收到endInterruption事件。苹果的文档让你认为在接听电话时可能不会收到endInterruption事件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接